【问题标题】:Accessing static fields by using decltype [duplicate]使用 decltype 访问静态字段 [重复]
【发布时间】:2012-02-21 08:01:24
【问题描述】:

可能重复:
C++0x decltype and the scope resolution operator

使用 g++ 4.6.1 编译下一个示例:

#include <iostream>

struct A
{
    static const int v = 1;
};

int main()
{
    A a;
    std::cout << decltype(a)::v << std::endl;
}

会产生下一个编译错误:

error: expected primary-expression before 'decltype'
error: expected ';' before 'decltype'

这符合标准吗?或者,它是 g++ 的怪癖?

【问题讨论】:

  • 如果您输入了 A::v ,它还可以让您免于输入更多内容:D
  • @Mr.Anubis:如果是std::map&lt;this_long_type_name, that_long_template&lt;other_type_name&gt;&gt; m; auto a = m.begin();....那么写typename而不是decltype(a)会省钱吗?
  • @BenVoigt 不是真正的骗子,我不喜欢这个问题的答案。我的问题的答案就在那个问题中
  • @VJovic:除了他的类被命名为Foo而不是A,静态成员是i而不是v之外,没有任何区别。 litb 提供了第二种解决方法,std::identity。而“我的问题的答案就在那个问题中”也是被骗的理由。

标签: c++ g++ c++11 decltype


【解决方案1】:

编译器似乎无法识别 decltype 关键字。

G++ 4.6.1 足够新,可以包含decltype 关键字。您是否使用-std=gnu++0x-std=c++0x 启用了C++11 模式?

C++ 语法确实允许 decltype-specifier 出现在 qualified-id 中的 :: 之前,因此代码将被符合标准的编译器接受。错误信息是错误的,decltype(a)::v 是一个有效的qualified-id,它是一个primary-expression

作为一种解决方法,您可以使用 typedef。示例:http://ideone.com/clone/7FKUJ

【讨论】:

  • 是的,我启用了 c++0x std 编译。哦,好吧,我现在只使用 typedef 解决方法
  • @BenVoigt:编译器无法识别 decltype 关键字。
  • 您的 ideone 链接似乎已被删除(它只是链接到起始页)。你有没有机会记得你在那个输入中输入了什么?
  • @Default:这是一个骗子的问题,展示了如何使用typedef 作为一种解决方法(是的,ideone 在他们承诺“永远”保持可用后删除代码很烦人)
【解决方案2】:

它是标准的,或者至少,它肯定是。我相信已经提交了一份 DR,它可能已在最终标准中修复,但可能需要在下一个标准中修复。很简单,decltype:: 之前不是有效的语法产生式。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2020-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-07
  • 2015-03-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多