检测 C++ 中是否存在类型 [英] Detect if a type exists in C++
问题描述
我需要一个可以这样调用的模板:
I'd need a template which can be called like this:
int x = type_exists< std::vector<int> >::value;
如果 #include <vector>
在源代码中较早出现(显式或可传递),则应将 x 设置为 1,否则应将 x 设置为 0.
This should set x to 1 if #include <vector>
was present (either explicitly or transitively) earlier in the source, otherwise it should set x to 0.
是否可以用 C++ 来实现?我正在使用 GCC,所以 GCC 扩展也很好.
Is it possible to do it in C++? I'm using GCC, so GCC extensions are also fine.
稍微改变调用语法也可以.
It's also OK to change the call syntax a bit.
运行 C++ 编译器两次是不行的:首先只是为了确定我们是否遇到编译错误.
It's not OK to run the C++ compiler twice: first just to figure out if we get a compile error.
推荐答案
这不是您要找的,但它尽可能接近 type_exists
特性:
This is not what you are looking for, but it's as close as you can get to a type_exists
trait:
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 测试.
This does exactly what it is supposed to do. Tested with GCC 5.4.0.
这篇关于检测 C++ 中是否存在类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!