6

クラス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
}
4

3 に答える 3

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);
};

使用法:

#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;
}

注:とマークされた行では、書き込みによって、少なくとも 1 つ、場合によってはそれ以上の型引数を持つ任意の#1テンプレートをトレイトが受け入れるようにすることもできます。

template <typename, typename...> class Tmpl
于 2012-08-29T16:12:38.637 に答える