c++可变模板类终止

C++ variadic template class termination

本文关键字:终止 c++      更新时间:2023-10-16

半小时前我发现了可变模板参数,现在我完全被迷住了。

我有一个基于静态类的抽象微控制器输出引脚。我想组一些输出引脚,所以我可以处理它们作为一个引脚。下面的代码可以工作,但我认为我应该能够在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 );
   }   
};

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

template<>
class tee<> : public pin_output {
public:
   static void set( bool b ){}   
};

错误消息很长,但它实际上表示没有牙齿<>。是我的牙齿有问题吗<>还是不可能结束递归

一般情况下至少需要1个参数(pin),因此您不能创建具有0个参数的专门化。

相反,您应该使用最通用的情况,接受任何数量的参数:

template< typename... > class tee;

创建专门化:

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