decltype可以用来命名方法的类吗?

问题描述 投票:0回答:1

使用

-std=c++23
,gcc 接受以下代码,而 clang 拒绝它:

struct outer {
  struct {
    int x;
    inline int get_x() const;
  } inner;
};

inline int
decltype(outer::inner)::get_x() const
{
  return x;
}

具体来说,clang 18.1 抱怨:

nested.cc:9:25: error: 'decltype' cannot be used to name a declaration
    9 | decltype(outer::inner)::get_x() const
      | ~~~~~~~~~~~~~~~~~~~~~~  ^

也就是说,两个编译器都接受使用类型别名,如下所示:

using inner_type = decltype(outer::inner);
inline int
inner_type::get_x() const
{
  return x;
}

哪个(如果有的话)编译器是正确的,为什么? 我可以使用任何技巧来避免为未命名结构的外线方法定义创建类型别名,或者在内部类型是私有的情况下使其工作吗?

请注意,与这个问题不同,我的嵌套名称说明符以decltype开头,因此这与询问为什么

outer::decltype(outer::inner)::...
无效(我已经理解)不同。 具体来说,上一个问题的答案是“除非在嵌套名称说明符的开头,否则 decltype 说明符永远不会出现”,这无助于解决在我的情况下哪种编译器是正确的或哪种语言的问题标准就是这样。 (或者,如果有的话,它表明了之前答案的相反——在我的例子中,gcc是正确的,而clang是不正确的。)

c++ language-lawyer decltype c++23
1个回答
0
投票

我认为该程序是格式错误,因为根据class.mfct

本地类的成员函数应在其类定义中内联定义(如果已定义)。

这意味着我们不允许为未命名的类提供成员函数的类外定义。

© www.soinside.com 2019 - 2024. All rights reserved.