fouronnes
fouronnes

Reputation: 4038

Class template parameter inference with constructor

I have the following template class :

template <typename T>
struct timer
{
    T period;

    timer(T p) :
        period(p)
    {}
};

To instantiate it I need to do :

timer<double> t(double(0.0));

Is is possible to improve timer's class definition to allow this syntax :

timer t(double(0.0));

and have the compiler infer the double type from the constructor's argument ?

Upvotes: 0

Views: 236

Answers (2)

mfontanini
mfontanini

Reputation: 21910

No, you can't do that. Type inference doesn't occur in those situations. You could use the auto keyword and a function template to make things easier though:

template<typename T>
timer<T> make_timer(T value) {
    return value;
}

// let the compiler deduce double
auto t = make_timer(0.0);

Note that this use of the auto keyword is only valid in the C++11 standard.

Moreover, for this specific situation, you could typedef a double timer:

typedef timer<double> timer_d;

timer_d t(0.0);

Though I'd still go with the first solution, if you're able to use C++11.

Upvotes: 3

Pubby
Pubby

Reputation: 53067

No, it's not possible, deduction only works in functions. The usual solution is to write a make_ function which returns a new instance. This is C++11:

template <typename T>
timer<T> make_timer(T&& p) {
  return timer<T>(std::forward<T>(p));
}

auto t = make_timer(0.0);

Upvotes: 3

Related Questions