简体   繁体   中英

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 ?

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM