Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ variadic template class termination

Half an hour ago I discovered variadic template parameters and now I am totally hooked.

I have a static class based abstraction for a microcontroller output pin. I want to group a number of output pins so I can handle them as one pin. The code below works, but I think I should be able to end the recursion on 0 parameters instead of on 1.

template< typename pin, typename... tail_args >
class tee {
public:

   typedef tee< tail_args... > tail;

   static void set( bool b ){
      pin::set( b );
      tail::set( b );   
   }   

};

template< typename pin >
class tee< pin > {
public:

   static void set( bool b ){
      pin::set( b );
   }   

};

I tried this but the compiler (gcc) seems not to take it into account:

template<>
class tee<> : public pin_output {
public:

   static void set( bool b ){}   

};

The error message is long, but it essentially says that there is no tee<>. Is there something wrong with my tee<> or isn't it possible to end the recursion

like image 606
Wouter van Ooijen Avatar asked Jun 07 '13 19:06

Wouter van Ooijen


1 Answers

Your most general case takes at least 1 argument (pin), so you cannot create a specialization, that has 0 arguments.

Instead, you should make most general case, that accepts any amount of arguments:

template< typename... > class tee;

And then create specializations:

template< typename pin, typename... tail_args >
class tee<pin, tail_args...> {
public:

   typedef tee< tail_args... > tail;

   static void set( bool b ){
      pin::set( b );
      tail::set( b );   
   }   

};

template<>
class tee<> {
public:

   static void set( bool b ){}   

};
like image 76
Lol4t0 Avatar answered Oct 13 '22 07:10

Lol4t0