仅接受某个类的继承人的模板函数

Mat*_*nti 4 c++ inheritance templates

在 C++ 中,假设我有一些 class mom。我知道我可以创建一个接受任何类的模板函数,例如:

template <class T> void Iacceptanything(T x)
{
  // Do something
}
Run Code Online (Sandbox Code Playgroud)

现在,这很好用,但我想创建一个更严格的模板类,它接受T从 class 继承的任何类型mom。我考虑过让函数接受mom作为唯一的参数类型,但在该函数中,我需要使用参数构建一个模板对象,因此我需要保留它的类型(即,我的对象不应该被“修剪”为只是它是 ) 的继承人mom

我需要的是这样的:

template <class T:mom> void Iacceptonlysonsofmom(T x)
{
    // Do something
}
Run Code Online (Sandbox Code Playgroud)

这有可能吗?

kec*_*kec 5

使用std::enable_ifstd::is_base_of.

#include <type_traits>
#include <iostream>

class Base { };
class Derived : public Base { };
class NotDerived { };

// If the return type of foo() is not void, add where indicated.
template <typename T>
typename std::enable_if<std::is_base_of<Base, T>::value /*, some_type*/>::type
foo(T) {
    std::cout << "Derived from Base." << std::endl;
}

// If the return type of foo() is not void, add where indicated.
template <typename T>
typename std::enable_if<!std::is_base_of<Base, T>::value /*, some_type*/>::type
foo(T) {
    std::cout << "Not derived from Base." << std::endl;
}

int
main() {
    Derived d;
    NotDerived nd;

    foo(d);
    foo(nd);
}
Run Code Online (Sandbox Code Playgroud)