1

I'm toying with some type safety ideas using the following code which converts between related units . . .

#include <cmath>
#include <limits>

template <typename T>
class Pascal
{

private:
    T val;

public:
    explicit Pascal(const T val_)
    {
        val = val_;
    }

    operator T() const
    {
        return val;
    }

};

template <typename T>
class dbSPL {
private:
    T val;

public:
    explicit dbSPL(const Pascal<T> p)
    {
        auto infProtect = std::numeric_limits<T>::min();
        val = 20.0 * std::log10( infProtect + p / 20e-6 );
    }


    operator T() const
    {
        return val;
    }


};

I want to know if it is possible to infer the template type from the constructor argument type, rather than explicitly declaring the template parameters. For example auto p = Pascal(0.5) rather than typing auto p = Pascal<double>(0.5), which would then lead to the neater dbSPL(Pascal(0.5)) over the more verbose dbSPL<double>(Pascal<double>(0.5)).

0

4 Answers 4

6

Use a helper function instead:

template <typename T>
dbSPL<T> make_dbspl(T t)
{
    return dbSPL<T>(Pascal<T>(t));
}

int main()
{
    auto dbspl = make_dbspl(0.5);
}

DEMO

1

One approach to solving this would be to create factory functions that are templated over the parameter types, and then return the dimensionalized types

1

As others said use wrapper function for this. What I would add is that this approach is used even in c++ standard library, e.g. std::make_pair or std::make_shared in c++11. Reason for this is that when you write declaration like T t(x); then T is a type name and for templates type name contains template parameters. Additionally if T constructor is template itself then this constructor template parameters would be infered from type of x no template parameter of T itself.

1

I want to know if it is possible to infer the template type from the constructor argument type, rather than explicitly declaring the template parameters

No.

Neither the syntax nor the semantics of the language do or can support this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.