Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading template classes by template parameter number

Tags:

Is it possible to have multiple versions of the same class which differ only in the number of template arguments they take?

For instance:

template<typename T> class Blah { public:     void operator()(T); };  template<typename T, typename T2> class Blah { public:     void operator()(T, T2); }; 

I'm trying to model functor type things which can take a variable number of arguments (up to the number of different templates that were written out).

like image 526
Seth Carnegie Avatar asked Aug 08 '11 21:08

Seth Carnegie


People also ask

Can class templates be overloaded?

A template function can be overloaded either by a non-template function or using an ordinary function template.

How many template parameters are allowed in a template classes?

Explanation: Just like normal parameters we can pass more than one or more template parameters to a template class.

How do you overload a template function?

You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.

Can a template be a template parameter?

Templates can be template parameters. In this case, they are called template parameters. The container adaptors std::stack, std::queue, and std::priority_queue use per default a std::deque to hold their arguments, but you can use a different container.


1 Answers

The simplest answer would be to have just one template, with the maximum number you want to support and use void for a default type on all but the first type. Then you can use a partial specialization as needed:

template<typename T1, typename T2=void> struct foo {     void operator()(T1, T2); };  template <typename T1> struct foo<T1, void> {      void operator()(T1); };  int main() {    foo<int> test1;    foo<int,int> test2;    test1(0);    test2(1,1); } 
like image 196
Flexo Avatar answered Nov 15 '22 13:11

Flexo