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

标签 c++ c++11 visual-c++ visual-studio-2015 strongly-typed-enum

我主要使用 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/

相关文章:

C++,协作 FILE* 和 std 流

c++ - 错误 C2106 : '=' : left operand must be l-value c++

c++ - 删除自身内的 std::function 对象

visual-c++ - fatal error LNK1179 : invalid or corrupt file: duplicate COMDAT '_IID_IXMLDOMImplementation'

c++ - 一个 SSE Stdlib 式的库?

c++ - 引用函数按值返回和自动

c++ - OpenGL 中的天空盒

c++ - clang 3.2 在 std::atomic 上失败——一个 libc++ 问题?

opencv - opencv 2.4.9和vs 2012中运行源人脸检测时出错

c++ - 调用 ConnectDirect() MSFT API 时出现错误 "The owner SID on a per-user subscription doesn' t 存在于 DXVA2 中,但不存在于 DXVAHD 中。