【问题标题】:C++ variadic template class terminationC++ 可变参数模板类终止
【发布时间】:2013-06-07 19:44:33
【问题描述】:

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

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

};

错误信息很长,但它本质上说没有 tee。我的 tee 有问题还是不能结束递归

【问题讨论】:

  • 您使用的是什么版本的 GCC?是 GCC 4.8 吗?您是否通过了 -std=c++11 标志(也带有 -Wall)?
  • 你的类型应该是template &lt;typename ...&gt; class tee,你的终止案例应该是template &lt;&gt; class tee&lt;&gt; { };
  • @Basile: 4.7.2;我用 -std=c++0x;使用 -std=c++11 -Wall 没有改变;
  • @Kerrek:当我的类型是 template class tee 时,我如何识别/使用该列表的“头部”?编辑:阅读 Lol4t0 的回答后,我有点理解你的意思,但我不知道我应该使用 2 个专业。

标签: c++ templates template-meta-programming


【解决方案1】:

您最一般的情况至少需要 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 ){}   

};

【讨论】:

  • 太棒了,就像一个魅力,我是我前进的一小步:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多