[英]c++ Restricting multiple template class types to derived classes
I was following template class restriction , but ran into errors in gcc: 我正在遵循模板类限制 ,但在gcc中遇到错误:
error: multiple types in one declaration 错误:一个声明中有多个类型
error: declaration does not declare anything 错误:声明不声明任何内容
It compiles if I remove the enable_if block. 如果我删除enable_if块,它会编译。 Can anybody explain if I am missing something?
任何人都可以解释我是否遗漏了什么?
template<class A, class B, class C, class D>
typename std::enable_if<
std::is_base_of<baseofA, A>::value &&
std::is_base_of<baseofB, B>::value &&
std::is_base_of<baseofC, C>::value &&
std::is_base_of<baseofD, D>::value>::type
class library {
//whatever
};
You're not using enable_if
correctly. 你没有正确使用
enable_if
。 static_assert
would be more appropriate in this case. 在这种情况下,
static_assert
会更合适。
template<class A, class B, class C, class D>
class library {
static_assert(
std::is_base_of<baseofA, A>::value &&
std::is_base_of<baseofB, B>::value &&
std::is_base_of<baseofC, C>::value &&
std::is_base_of<baseofD, D>::value,
"template argument A must derive from baseofA and so on ..." );
//whatever
};
If you want to use enable_if
instead you must create a dummy template parameter that depends on the enabled type for it to work as you desire. 如果要使用
enable_if
则必须创建一个虚拟模板参数,该参数取决于启用的类型,以使其按您的需要工作。
template<class A,
class B,
class C,
class D,
class _ =
typename std::enable_if<
std::is_base_of<baseofA, A>::value &&
std::is_base_of<baseofB, B>::value &&
std::is_base_of<baseofC, C>::value &&
std::is_base_of<baseofD, D>::value>
::type>
class library {
//whatever
};
But IMO, the static_assert
method is better because you can provide a descriptive error message instead of the compiler complaining about failing to find a type named type
in the latter case. 但IMO,
static_assert
方法更好,因为您可以提供描述性错误消息,而不是编译器抱怨在后一种情况下未能找到名为type
。
Following this page, try 点击此页面,试试吧
template<class A, class B, class C, class D, class Enable = void>
class library;
template<class A, class B, class C, class D>
class library<A, B, C, D, typename std::enable_if< std::is_base_of<baseofA, A>::value &&
std::is_base_of<baseofB, B>::value &&
std::is_base_of<baseofC, C>::value &&
std::is_base_of<baseofD, D>::value >::type
>
{
//whatever
};
Note that there must be something wrong with your example, since enable_if<>::type is a type, which you wouldn't want between the template<> line and the class library line. 请注意,您的示例必定存在问题,因为enable_if <> :: type是一种类型,您不希望在模板<>行和类库行之间使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.