For each type of template, a set type argument is used.

Say I have a variational template class. How to create a function so that its arguments have a set type, for example, int , the number of arguments equal to the number of template types?

 template <typename... Types> class Test { public: void Func(???); // I don't know how to declare such a function } Test<string, bool, long> myTest; // Three types myTest.Func(905, 36, 123315); // Three arguments, but always of type int. 

In the end, the purpose of the function is to return a tuple of the provided ints. For simplicity, I have shown that the function is not valid in the sample code.

+7
c ++ variadic-templates
source share
2 answers
 template <typename... Types> class Test { template <typename> using int_t = int; public: void Func(int_t<Types>... ints) { } }; 

Demo

+17
source share

wandbox example - (works with C ++ 11)


If you do not require SFINAE, you can use static_assert to make sure your conditions are met:

 template <typename... Types> class Test { public: template <typename... Ts> void Func(Ts...) { static_assert(sizeof...(Ts) == sizeof...(Types), ""); static_assert(std::conjunction<std::is_same<Ts, int>...>{}, ""); } }; 

(If you need SFINAE, use std::enable_if .)

std::conjunction checks that all conditions passed to it are true.


In the above example, the following calls are valid / invalid:

 myTest.Func(905, 36, 123315); // valid myTest.Func(905, 36, 123315.f); // invalid myTest.Func(905, 22); // invalid 

As you can see, implicit conversions are not allowed by this solution. You can use std::is_convertible instead of std::is_same if you want them to be allowed.

+4
source share

All Articles