【问题标题】:Why does scope resolution fail in presence of decltype?为什么存在 decltype 时范围解析会失败?
【发布时间】:2013-07-04 04:17:15
【问题描述】:

据我了解,decltype 用于查询对象/变量的类型等。

来自维基百科上的示例,例如:

int i;
decltype(i) x3; // type is int

我以为我可以这样做:

class A
{
public:
    int a, b;
};

template<typename T>
struct IsClass
{
    enum { Yes = std::is_class<T>::value };
    enum { No = !Yes };
};

std::vector<A> v;
auto it = v.begin();
IsClass<decltype(it)::value_type>::Yes

因为毕竟这行是合法的:

IsClass<std::vector<A>::iterator::value_type>::Yes

唉,它不会编译,引用以下内容:error C2039: 'value_type' : is not a member of 'global namespace''`

关于为什么在 decltype 存在的情况下进行范围解析以这种方式表现的任何想法?

P.S:如果有什么不同,我使用的是 MSVC2012(没有 Nov CTP)

【问题讨论】:

  • gccclang 似乎接受了这一点:coliru.stacked-crooked.com/…
  • @ShafikYaghmour 我刚刚将它粘贴到我正在使用的 MSVC2012 中(我为此添加了注释),但它无法编译。
  • MSVC 确实很糟糕,他们在实施标准方面没有取得与 gcc 和 clang 相同的进展
  • 虽然可以编译:IsClass&lt;std::remove_reference&lt;decltype(it)&gt;::type::value_type&gt;::Yes; 我的猜测是,虽然它应该是一个值类型,但 MSVC 错误地在这里为decltype(it) 生成了一个引用类型。
  • 这是一个已知问题。试试typedef decltype(it) itType 然后使用它。

标签: c++ c++11 decltype


【解决方案1】:

这是 Visual C++ 编译器中的一个已知错误。从 Visual C++ 2013 Preview 开始,它还没有被修复。您可以使用std::common_type 解决此问题:

IsClass<std::common_type<decltype(it)>::type::value_type>::Yes
        ^^^^^^^^^^^^^^^^^            ^^^^^^^

(带有单个模板参数的std::common_type 会产生该参数类型;它是标准的 C++11 等价物,与长期以来在元编程中使用的 identity 模板等效。)

您可以在 Microsoft Connect 上找到公共错误报告:Cannot use decltype before scope operator。如果此问题对您很重要,请考虑支持该错误报告。

【讨论】:

  • 还是不明白为什么不能叫它std::identity。你知道,和其他人一样。
  • @LightnessRacesinOrbit:之前有一个std::identity,但由于不清楚它到底应该是什么而被删除(只是元编程身份,比如std::common_type&lt;T&gt;现在是?功能身份?) ,IIRC。
  • @Lightness Races in Orbit:看起来并不像如何“称呼”它。 std::common_type 的功能比std::identity 更广泛。它也仅涵盖std::identity。所以问题实际上是是否将std::identity 保留为具有更漂亮名称的东西,或者将其删除为多余的东西。他们删除了它。
  • @LightnessRacesinOrbit:除了“让我们不要添加无关的东西”论点之外,identitythe original STL 中已经有了另一个含义。不过我同意,如果有std::identity 就好了。这确实会让事情更容易解释。
  • @James: 啊,STL 的论点已经确定了。混蛋!
猜你喜欢
  • 2011-07-28
  • 2016-11-22
  • 2021-09-26
  • 2017-05-14
  • 2019-09-06
  • 2021-06-03
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
相关资源
最近更新 更多