Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

c++ - How to test whether class B is derived from template family of classes

How to test at compile time whether class B is derived from std::vector?

template<class A>
struct is_derived_from_vector {
  static const bool value = ????;
};

How to test at compile time whether class B is derived from template family?

template<class A, template< class > class Family>
struct is_derived_from_template {
  static const bool value = ????;
};

Using:

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this:

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

Usage:

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

Note: In the line marked #1, you could also make your trait accept any template that has at least one, but possibly more type arguments by writint:

template <typename, typename...> class Tmpl

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...