有一些课程,他们的关系如下:
class X:A,B
class Y:A,B
class Z:A,B
我想使用模板将从A和B继承的常规类型传递给testFunction。我的代码如下:
template<template T:public A, public B>
void testFunction(T generalType)
{
//do something
}
但我的编译器告诉我它是错误模板。我怎么能解决它?
答案 0 :(得分:9)
有条件地定义模板的标准方法是std::enable_if<condition>
。在这种情况下,您要检查条件std::is_base_of<A,T>::value && std::is_base_of<B,T>::value
答案 1 :(得分:4)
template<template T:public A, public B>
是无效的语法。您可以使用std::is_base_of
和static_assert
检查类型,如果传递了错误的类型,将触发编译器错误。
template <typename T>
void testFunction(T generalType)
{
static_assert(std::is_base_of<A, T>::value && std::is_base_of<B, T>::value, "T must inherit from A and B.");
}