如何在编译时测试B类是否源自std :: vector?如何测试B类是否来自类的模板族
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'就是例如ony。如果您不了解C++ 03解决方案,那么也欢迎C++ 11解决方案。 –