【发布时间】:2012-08-29 15:54:00
【问题描述】:
如何在编译时测试B类是否派生自std::vector?
template<class A>
struct is_derived_from_vector {
static const bool value = ????;
};
如何在编译时测试B类是否来自模板族?
template<class A, template< class > class Family>
struct is_derived_from_template {
static const bool value = ????;
};
使用:
template<class T> struct X {};
struct A : X<int> {}
struct B : std::vector<char> {}
struct D : X<D> {}
int main() {
std::cout << is_derived_from_template<A, X>::value << std::endl; // true
std::cout << is_derived_from_template<D, X>::value << std::endl; // true
std::cout << is_derived_from_vector<A>::value << std::endl; // false
std::cout << is_derived_from_vector<B>::value << std::endl; // true
}
【问题讨论】:
-
对于模板元编程,重要的是要明确说明您是否只需要 C++03 或 C++11 解决方案是好的(尽管我不确定 C++11 是否可以提供帮助)这里)。作为一个聪明的评论,鉴于你永远不应该从标准容器继承原始特征很简单:
false:P -
C++03.我使用 msvc 2010 编译器。因此我同意另外使用
decltype。std::vector例如只有一个。如果您不知道 C++03 解决方案,那么也欢迎使用 C++11 解决方案。
标签: c++ templates sfinae typetraits c++03