c++检查模板参数是否从某个基类派生
c++ check that templates parameters are derived from a certain base class
如何检查模板参数是否从某个基类派生?所以我确信函数Do可以被调用:
template<typename Ty1> class MyClass
{
...
void MyFunction();
};
template<typename Ty1> void MyClass<Ty1>::MyFunction()
{
Ty1 var;
var.Do();
}
不要。如果方法Do()
不存在于作为Ty1
参数提供的类中,则它将无法编译。
模板是鸭类型的一种形式:类的能力不是由它继承的接口决定的,而是由它实际暴露的功能决定的。
的优点是,你的模板可以被任何类使用一个合适的Do()
方法,不管它来自哪里或它有什么基础。
您可以使用标准类型trait is_base_of来实现这一点。请看下面的例子:
#include <iostream>
#include <type_traits>
using namespace std;
class Base {
public:
void foo () {}
};
class A : public Base {};
class B : public Base {};
class C {};
void exec (false_type) {
cout << "your type is not derived from Base" << endl;
}
void exec (true_type) {
cout << "your type is derived from Base" << endl;
}
template <typename T>
void verify () {
exec (typename is_base_of<Base, T>::type {});
}
int main (int argc, char** argv) {
verify<A> ();
verify<B> ();
verify<C> ();
return 0;
}
输出为:
your type is derived from Base
your type is derived from Base
your type is not derived from Base
相关文章:
- 指向基类派生类的 std::unique_ptr 的指针
- 从多个模板化基类派生时出现"隐藏重载的虚函数"警告
- 从模板基类派生是否在派生类声明的点实例化模板
- 使从一个基类派生的类能够使用继承的受保护成员
- C++多态性访问基类派生类字段
- C++派生类的设置属性到从同一基类派生的未知类对象
- 使用void* 参数定义纯虚函数的抽象基类.派生类匹配参数是指向某种类型的指针
- 在C++中,如何使用将保存从基类派生的任何对象的类成员
- 如何测试从依赖于外部系统的外部基类派生的类
- 如何从模板基类派生非模板类
- 在派生类中使用声明并不能隐藏从基类派生的相同函数
- 从具有静态结构的基类派生
- 具有从 c++ 中的非模板基类派生的模板类的事件系统
- C++ 调用从基类派生的覆盖函数
- 不清楚如何在从抽象基类派生的类中实现运算符重载
- 如何正向声明从正向声明的模板基类派生的类
- 是否可以从 std::enable_shared_from_this 和抽象基类派生
- 多态性c++,试图访问从抽象基类派生的类的成员函数
- C++多重继承,基类派生自同一类
- 基类派生类访问-如何