Reputation: 81
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?
Upvotes: 4
Views: 87
Reputation: 172904
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.");
}
Upvotes: 4
Reputation: 179799
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
Upvotes: 9