半小时前我发现了可变模板参数,现在我完全着迷了。
我有一个基于静态类的微 Controller 输出引脚抽象。我想将一些输出引脚组合在一起,这样我就可以将它们作为一个引脚来处理。下面的代码有效,但我认为我应该能够在 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<> 有问题,或者不能结束递归
最佳答案
您的最一般情况至少需要 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 ){}
};
关于C++ 可变参数模板类终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16991853/