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 ?
No, you can’t do that. Type inference doesn’t occur in those situations. You could use the
autokeyword and a function template to make things easier though:Note that this use of the
autokeyword is only valid in the C++11 standard.Moreover, for this specific situation, you could
typedefadoubletimer:Though I’d still go with the first solution, if you’re able to use C++11.