c – 如何测试B类是否来自模板族类

如何在编译时测试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
}

解决方法

试试这个:
#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的行中,您还可以使您的特征接受任何具有至少一个但可能更多类型参数的模板:writint:

template <typename,typename...> class Tmpl

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...