How to test whether class B is derived from template family of classes(如何测试类 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;
}
注意:在标记为 #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 是否派生自类的模板族的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何测试类 B 是否派生自类的模板族


基础教程推荐
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01