问题描述
假设我有一个带有以下签名的类:
Suppose I have a class with the following signature:
template <typename T, typename... Args>
class A;
但是此类的行为方式应取决于其他一些参数,比如说它是 T :: value
:
But how this class behaves should depend on some other parameter, let's say it's the value of T::value
:
template <typename T, typename... Args, typename Enable>
class A;
template <typename T, typename... Args, typename = typename std::enable_if<T::value>::type>
class A
{
// do something
};
template <typename T, typename... Args, typename = typename std::enable_if<!T::value>::type>
class A
{
// do something else
};
int main() { return 0; }
但是,此程序出现以下错误:
However, this program gives the following error:
我一直在努力寻找有关使用 enable_if
选择带有可变参数模板的类的良好信息资源.我唯一能找到的问题就是这个:
I have struggled to find a good source of information on the use of enable_if
to select classes with variadic templates. The only question I could find is this one:
如何将std :: enable_if与可变参数模板一起使用
但是,尽管有这个名字,这个问题及其答案并没有多大帮助.如果有人可以提供或链接有关如何进行此操作的指南以及为什么会对此表示赞赏.
But despite the name, this question and its answers aren't much help. If someone could provide or link a guide on how this should be approached and why that would be appreciated.
推荐答案
首先,您要尝试编写类模板的多个定义.不允许这样做,因为它违反了一个定义规则.如果要对类进行条件启用,则需要特殊化.另外,编译器错误消息已经告诉您,参数列表中间不能有可变参数包.
First of all, what you're trying is writing multiple definitions of a class template. That's not allowed because it violates One definition rule. If you want to do conditional enabling with classes, you need specializations. Also, the compiler error message already told you, you can't have a variadic parameter pack in the middle of a parameter list.
一种方法是:
namespace detail {
template<typename T, typename Enable, typename... Args>
class A_impl;
template<typename T, typename... Args>
class A_impl<T, typename std::enable_if<T::value>::type, Args...> {
// code here
};
template<typename T, typename... Args>
class A_impl<T, typename std::enable_if<!T::value>::type, Args...> {
// code here
};
}
template<typename T, typename...Args>
class A : public detail::A_impl<T, void, Args...> {};
乔纳森的方法如果条件确实是 bool
的话,也很好.如果您希望添加更多的专业化专业,而每个专业化专业都取决于几个条件,则可能没有用.
Jonathan's way is also perfectly fine if the condition is really a bool
, but it might not be useful if you wish to add more specializations that each depend on several conditons.
这篇关于如何启用带有可变模板参数的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!