使用模板将一般参数传递给函数

时间:2016-04-26 10:15:55

标签: c++ templates

有一些课程,他们的关系如下:

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
}

但我的编译器告诉我它是错误模板。我怎么能解决它?

2 个答案:

答案 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_ofstatic_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.");
}

DEMO