4

There are some classes and their relationships are as follows:

class X:A,B
class Y:A,B
class Z:A,B

I want to pass a general type that will inherit from A and B to testFunction using template. My code is as follows:

template<template T:public A, public B>
void testFunction(T generalType)
{
    //do something
}

but my compiler told me that it's error template. How could I fix it?

rontgen
  • 81
  • 1
  • 9
  • Reopened this - the supposed duplicate was about a _class_. But unlike classes, functions have overloading. That means you want to _exclude_ specific functions from the overload set, rather then have them be selected in overload resolution and then break later on. – MSalters Apr 26 '16 at 10:21
  • 3
    Why not simply write `template – Aaron McDaid Apr 26 '16 at 10:39
  • @ MSalters @ Aaron McDaid @songyuanyao. Thanks for all of your patient and careful answers. With all your help, my code pass the stage of compilation. I have learned a lot from all of you, – rontgen Apr 27 '16 at 01:36

2 Answers2

9

The standard method to conditionally define a template is std::enable_if<condition>. In this case, you want to check the condition std::is_base_of<A,T>::value && std::is_base_of<B,T>::value

MSalters
  • 173,980
  • 10
  • 155
  • 350
4

template<template T:public A, public B> is not valid syntax. You could check the type with std::is_base_of and static_assert, which will trigger a compiler error if wrong type passed.

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

songyuanyao
  • 169,198
  • 16
  • 310
  • 405