给定以下代码序列:
#include <iostream>
using namespace std;
template <typename T>
class Base
{
public:
T* t;
void b() {}
};
class D1:
public Base<D1>
{
public:
int d1;
};
class D2:
public D1
{
public:
int d2;
};
template <typename T>
class Selector
{
public:
template <typename U>
void a(Base<U>& base)
{
cout << __LINE__ << endl;
base.b();
}
template <typename U>
void a(U& u)
{
cout << __LINE__ << endl;
}
};
int main()
{
D2 derivated;
Selector<D2> s;
s.a(derivated);
return 0;
}
我想检查某些类 (D2) 是否有基类 (Base) 继承了任何 D2 父类。
我只是无法让 Selector
命中最专业的成员函数。
最佳答案
您可以设置自己的特征来检查类型是否有任何 Base<T>
作为祖先。以下对我有用:
template <typename T> struct Foo { };
struct Bar : Foo<Bar> { };
struct Zip : Bar { };
#include <type_traits>
template <typename T>
class derives_from_any_foo
{
typedef char yes;
typedef char no[2];
template <typename U>
static yes & test(Foo<U> const &);
static no & test(...);
public:
static bool const value = sizeof(test(std::declval<T>())) == sizeof(yes);
};
#include <iostream>
int main()
{
std::cout << "int: " << derives_from_any_foo<int>::value << "\n"
<< "Bar: " << derives_from_any_foo<Bar>::value << "\n"
<< "Zip: " << derives_from_any_foo<Zip>::value << "\n";
}
通常不需要任何对象实例来进行这些类型检查;一切都是静态的。如果您有对象,请使用 decltype
获取其类型,或添加类型推导辅助函数。
关于c++ - 使用模板化基础编译时间类选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13233400/