如何测试类B是否派生自类的模板族 [英] How to test whether class B is derived from template family of classes

查看:84
本文介绍了如何测试类B是否派生自类的模板族的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在编译时测试类B是否来自std :: vector?

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 = ????;
};

如何在编译时测试类B是否派生自模板族?

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 = ????;
};

使用:

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
}


推荐答案

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

注意: $ c>#1 ,您也可以让您的trait接受至少有一个,但可能有更多类型参数的writint的任何模板:

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

这篇关于如何测试类B是否派生自类的模板族的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆