检测C++中是否存在类型
Detect if a type exists in C++
我需要一个可以这样调用的模板:
int x = type_exists< std::vector<int> >::value;
如果#include <vector>
早在源中(显式或传递式)存在,则应将x设置为1,否则应将x设为0。
用C++做这件事可能吗?我使用的是GCC,所以GCC扩展也不错。
稍微更改一下调用语法也是可以的。
运行C++编译器两次是不好的:第一次只是为了弄清楚是否出现编译错误。
这不是你想要的,但它尽可能接近type_exists
特征:
template<class T> struct Void { typedef void type; };
template<class T, class U = void>
struct type_exists { enum { value = 0 }; };
template<class T>
struct type_exists<T, typename Void<T>::type> { enum { value = 1 }; };
显然,它是有效的:
static_assert(type_exists<int>::value, "int is not defined");
static_assert(type_exists<SomeNonexistingType>::value, "expected compile-time error");
这正是它应该做的。用GCC 5.4.0测试。
恐怕这是不可能的。如果我们使用未定义的标识符,我们将得到一个编译错误,导致以下代码:
int x = type_exists< std::vector<int> >::value;
甚至不编译。
此外,该标准没有指定要在标准库的头文件(而是由实现定义的)中声明的任何预处理器指令,因此即使使用预处理器宏也无法检测到它。
相关文章:
- C++LinkedList问题.数据类型之间存在冲突?没有匹配的构造函数
- 迭代时将指向differents类型的指针保存在std::向量中
- 使用SFINAE来检测void返回类型函数的存在
- 将字符串转换为整数类型T,检查是否存在溢出
- 指向类成员函数的指针中存在类型转换错误
- 输出 [left]=input[i] 行中的 c++ 代码中存在无效的类型错误
- 是否存在 x + 1 == x 类型的浮点型值 x
- 仅当元组中存在该类型时,将功能应用于元组元素
- 使用 SFINAE 检查函数 std::to_string 是否存在类型
- 对条件表达式结果的赋值(其中第二个和第三个操作数是相同类型和值类别的变量)是否仍然存在?
- Clang和GCC在转换C++17中非类型模板参数的自动说明符中存在分歧
- 根据成员变量的类型是否存在,有条件地定义该变量
- 为什么与非类型参数相反,为什么不可见/存在模板类型参数
- C 编译时间检查模板类型中是否存在方法
- 错误:"参数"没有命名类型,.cpp和 .h 文件可能存在问题
- 模板类根据其他类的存在性和优先级以及更多的类型限制(如常量和区分大小写)调用其他类的某些函数
- C 检测是否存在接受特定类型的函数
- 检测C++中是否存在类型
- 为什么我的静态方法的返回值与定义的构造函数(在 c++ 中)之间存在类型不匹配?
- 是否存在类型的静态向量