【问题标题】:Detect if a type exists in C++ [duplicate]检测 C++ 中是否存在类型 [重复]
【发布时间】:2013-12-15 11:03:25
【问题描述】:

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

int x = type_exists< std::vector<int> >::value;

如果#include &lt;vector&gt; 早先在源中存在(显式或传递),则应将 x 设置为 1,否则应将 x 设置为 0。

可以用 C++ 实现吗?我使用的是 GCC,所以 GCC 扩展也可以。

稍微改变一下调用语法也可以。

两次运行 C++ 编译器是不行的:首先只是为了弄清楚我们是否得到了编译错误。

【问题讨论】:

  • 你会用这样的功能做什么?
  • 一般情况下,您只能使用已声明的 C++ 中的名称。语言中没有通用的“反射”或“裸词”支持,可以让您检查解析器的状态。对于类模板成员来说有点不同,但很特别。
  • @pts 正如对has_destructor 的明确解释,您需要声明要测试的名称,然后它可以工作:coliru.stacked-crooked.com/a/4b39006dfae715d0。如main 的第二部分所示,一个潜在的问题是,如果您声明一个已定义的类,则必须在定义的相同范围(和命名空间)内进行。
  • @gx_:has_destructor 如何为vector&lt;int&gt; 这样的模板工作?我该如何预先声明?

标签: c++ template-meta-programming sfinae typetraits


【解决方案1】:

这不是你要找的,但它与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 测试。

【讨论】:

  • 确实,对于type_exists 的定义,如果不包含&lt;vector&gt;int x = type_exists&lt; std::vector&lt;int&gt; &gt;::value; 将无法编译,所以这并不能解决我的问题。
【解决方案2】:

恐怕这是不可能的。如果我们使用一个未定义的标识符,我们会得到一个编译错误,导致这个代码:

int x = type_exists< std::vector<int> >::value;

甚至不编译。

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

【讨论】:

    猜你喜欢
    • 2010-12-01
    • 2012-10-25
    • 2011-12-31
    • 2014-09-11
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多