在 C++ 中,假设我有一些类 mom
。我知道我可以制作一个接受任何类的模板函数,例如:
template <class T> void Iacceptanything(T x)
{
// Do something
}
现在,这很好用,但我想制作一个限制性更强的模板类,它接受作为 T
继承自类 mom
的任何类型。我想过让函数接受 mom
作为唯一的参数类型,但是在那个函数中我需要用参数构建一个模板对象,因此我需要保留它的类型(即我的对象应该不要被“修剪”成只有它是 mom
的继承人)。
我需要的是:
template <class T:mom> void Iacceptonlysonsofmom(T x)
{
// Do something
}
这可能吗?
最佳答案
使用 std::enable_if
和 std::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);
}
关于c++ - 只接受某个类的继承人的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27576423/