Ale*_*tov 6 c++ templates sfinae type-traits c++03
如何在编译时测试B类是否来自std :: vector?
template<class A>
struct is_derived_from_vector {
static const bool value = ????;
};
Run Code Online (Sandbox Code Playgroud)
如何在编译时测试B类是否来自模板系列?
template<class A, template< class > class Family>
struct is_derived_from_template {
static const bool value = ????;
};
Run Code Online (Sandbox Code Playgroud)
使用:
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
}
Run Code Online (Sandbox Code Playgroud)
Ker*_* SB 12
试试这个:
#include <type_traits>
template <typename T, template <typename> class Tmpl> // #1 see note
struct is_derived
{
typedef char yes[1];
typedef char no[2];
static no & test(...);
template <typename U>
static yes & test(Tmpl<U> const &);
static bool const value = sizeof(test(std::declval<T>())) == sizeof(yes);
};
Run Code Online (Sandbox Code Playgroud)
用法:
#include <iostream>
template<class T> struct X {};
struct A : X<int> {};
int main()
{
std::cout << is_derived<A, X>::value << std::endl;
std::cout << is_derived<int, X>::value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
注意:在标记的行中#1,您还可以使您的特征接受任何具有至少一个但可能更多类型参数的模板:writint:
template <typename, typename...> class Tmpl
Run Code Online (Sandbox Code Playgroud)