c++ - A variadic template method to accept a given number of doubles? -
template <unsigned int n> class myclass { public: template <typename... args> void mymethod(args... args) { // interesting stuff } };
i want mymethod
called n doubles. possible? is, have:
myclass <3> x; x.mymethod(3., 4., 5.); // works x.mymethod('q', 1., 7.); // doesn't work x.mymethod(1., 2.); // doesn't work
how can done?
for number of arguments constraint can check if sizeof...(args) == n
checking if arguments doubles need build recursive type trait checks std::is_same
each of arguments.
template<typename...> struct are_same : std::true_type {}; template<typename t> struct are_same<t> : std::true_type {}; template<typename t, typename u, typename... types> struct are_same<t, u, types...> : std::integral_constant<bool, (std::is_same<t, u>::value && are_same<t, types...>::value)> {};
notice are_same
first declared , specialized.
then implement constraint in method return type using std::enable_if
taking advantage of sfinae.
template <unsigned int n> class myclass { public: template <typename... args> typename std::enable_if<(are_same<double, args...>::value && sizeof...(args) == n), void>::type /* void */ mymethod(args... args) { // interesting stuff } };
Comments
Post a Comment