Passing a generic argument to a function using a template

There are several classes, and their relationships are as follows:

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

I want to pass a generic type that will inherit from A and B to testFunction using a 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 this is an error pattern. How can i fix this?

+4
source share
2 answers

template<template T:public A, public B>is not valid syntax. You can check the type with std::is_base_ofand static_assert, which will cause a compiler error if the wrong type is 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

+4
source

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

+9

All Articles