检测C++中是否存在类型

Detect if a type exists in C++

本文关键字:存在 类型 是否 C++ 检测      更新时间:2023-10-16

我需要一个可以这样调用的模板:

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;

甚至不编译。

此外,该标准没有指定要在标准库的头文件(而是由实现定义的)中声明的任何预处理器指令,因此即使使用预处理器宏也无法检测到它。