【问题标题】:const dependent names returned from template functions, where does const go?从模板函数返回的 const 依赖名称,const 去哪里了?
【发布时间】:2016-05-08 19:30:15
【问题描述】:

假设我有一个模板函数(例如,foo),它返回一个 const 依赖类型。将返回类型限定为 const 的选项是将 const 放在 typename 关键字的左侧:

template<typename T>
const typename T::bar
^^^^^
foo(T const& baz) {
  ...
}

或在依赖类型的右侧:

template<typename T>
typename T::bar const
                ^^^^^
foo(T const& baz) {
  ...
}

但是如果我将const 限定符放在typename 关键字和依赖类型之间呢?

template<typename T>
typename const T::bar
         ^^^^^
foo(T const& baz) {
  ...
}

如预期的那样,无法为 GCC 和 CLANG 编译,但令我惊讶的是 VC++ 编译得很好。

问:

  • 这是 VC++ 扩展吗?
  • C++ 标准是否说明了在这种情况下将const 限定符放在哪里合适?

【问题讨论】:

    标签: c++ templates c++11 language-lawyer dependent-name


    【解决方案1】:

    C++ 标准是否说明了合适的位置 在这样的上下文中放置const 限定符的地方?

    是的。 typename 出现在 typename-specifier 中,whose production is

    typename nested-name-specifier 标识符
    typename nested-name-specifier template optsimple-template-id

    换句话说,它后面必须直接跟一个nested-name-specifier。不允许使用const

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-16
      • 2014-02-26
      • 2012-02-18
      • 2021-04-17
      • 1970-01-01
      • 2012-05-26
      • 1970-01-01
      相关资源
      最近更新 更多