0

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 ?

fouronnes
  • 3,838
  • 23
  • 41
  • 1
    check out [Why not infer template parameter from constructor?](http://stackoverflow.com/questions/984394/why-not-infer-template-parameter-from-constructor) for the same question – Karthik T Dec 07 '12 at 02:08

2 Answers2

3

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);
Pubby
  • 51,882
  • 13
  • 139
  • 180
3

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.

mfontanini
  • 21,410
  • 4
  • 65
  • 73