gpt4 book ai didi

c++ - 在成员函数的默认参数中使用强类型枚举的成员

转载 作者:搜寻专家 更新时间:2023-10-31 02:21:12 24 4
gpt4 key购买 nike

我主要使用 G++,现在使用 Visual Studio 2015。我想用 VC++2015 构建我的项目,但我收到错误消息,指出在给定默认参数的函数中无效使用“::”,并带有前向声明的强类型枚举。

这是一些代码:

struct Foo
{
//! Forward declaration of Bar
enum class Bar : short;

//! "Faulty" function with default argument
void DoSmth(Bar aBar = Bar::Baz)
{
// ... code ...
}

//! Complete declaration of Bar
enum class Bar : short
{
Baz
};
};

int main() { }

在使用默认参数 Bar::Baz 声明函数 DoSmth() 时出现以下错误:

test.cpp(7): error C2589: '::': illegal token on right side of '::'
test.cpp(7): error C2059: syntax error: '::'
test.cpp(17): fatal error C1903: unable to recover from previous error(s); stopping compilation

使用 G++(使用 4.9 和 5.1 测试)代码编译得很好,但使用 VC++2015 则不行。

我完全知道我必须在使用前声明一些东西但是。是否只是因为 VC++2015 没有在类的范围内查找 Bar 的完整声明和定义,而 G++ 有?或者 G++ 是否只是采用完整的声明并将其与前向声明“合并”(因为它们在同一范围内),从而使其完全可供类使用?或者也许我完全错了,是完全不同的原因造成的?

我可以接受我必须更改所有强类型枚举的声明才能使其与 VC++2015 一起工作。

但我也想知道这是为什么?

最佳答案

你的代码是有效的,VC 14拒绝它是错误的。

根据 N4527 ,当前标准工作草案,[9.2p2]:

A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors (12.9), exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

在默认参数中,查找 Bar::Baz 需要 Bar 的完整定义,它在完整类中可用,所以一切都很好。

关于c++ - 在成员函数的默认参数中使用强类型枚举的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31711385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com