c++ - 只接受某个类的继承人的模板函数

标签 c++ templates inheritance

在 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_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);
}

关于c++ - 只接受某个类的继承人的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27576423/

相关文章:

c++ - 迭代成员和调用作为参数传递的函数的函数

c++ - 这个关于类模板中静态的编译器错误是什么意思?

c++ - 专门模板类的 ostream 友元函数

c# - DataContract 将继承类型序列化为基类型

c++ - 如何避免两步初始化

c++ - qt rcc(资源编译器)是非确定性的——如何使其具有确定性

c++ - Matlab R2016a Mex 文件错误

c++ - 带排列的字符串操作

c++ - 告诉所有者绘制列表框重绘项目的最佳方式?

JavaScript 原型(prototype)构造函数仅调用一次