C++可变参数模板类终止

Wou*_*jen 6 c++ templates template-meta-programming

半小时前我发现了可变参数模板参数,现在我完全迷上了.

我有一个基于静态类的抽象,用于微控制器输出引脚.我想将多个输出引脚分组,以便将它们作为一个引脚处理.下面的代码有效,但我想我应该能够在0参数而不是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 );
   }   

};
Run Code Online (Sandbox Code Playgroud)

我试过这个,但编译器(gcc)似乎没有考虑到它:

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

   static void set( bool b ){}   

};
Run Code Online (Sandbox Code Playgroud)

错误消息很长,但它基本上说没有tee <>.我的T恤<>是否有问题,或者是否有可能结束递归

Lol*_*4t0 6

您最常见的情况至少需要1参数(pin),因此您无法创建具有0参数的特化.

相反,你应该做出一般情况,接受任意数量的参数:

template< typename... > class tee;
Run Code Online (Sandbox Code Playgroud)

然后创建专业化:

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 ){}   

};
Run Code Online (Sandbox Code Playgroud)