c++ - 不能在类范围内使用 `static_assert` 和 `sizeof`(但方法范围没问题)

标签 c++ g++

这是一个简单示例的摘录(请参阅 full source live here):

class Foo final {
    public:
        int var;

        inline Foo(void) {
            static_assert(sizeof(Foo)==sizeof(int),"Implementation error!");
        }

        static_assert(sizeof(Foo)==sizeof(int),"Implementation error!");
};

在最近的 g++ 上(注意 MSVC 没有提示),这会产生如下内容:

error: invalid application of ‘sizeof’ to incomplete type ‘Foo’

该错误发生在第二个static_assert 上。

我知道类的定义还没有词法写完,但是肯定有一个完整类型的所有信息,对吧?我的意思是,我们在里面。即使不是,为什么它会在方法中起作用?

最佳答案

类类型在它自己的成员函数体内是完整的(正如 Matt 所说,函数体的处理是延迟的)。它在类定义的 {} 内的大多数其他地方都不完整,包括那个 static_assert。 9.2 节的规则是

A class is considered a completely-defined object type (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.

想一想,编译器应该怎么知道你没有

int another_var;

紧接在 static_assert 之后?

static_assert 的最佳位置可能是在类定义之后的命名空间范围内。

关于c++ - 不能在类范围内使用 `static_assert` 和 `sizeof`(但方法范围没问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28576449/

相关文章:

c++ - std::adjacent_difference 与 std::chrono time_point

c++ - 如何在 OOP C++ 中使用 Const 类型类?

c++ - 在构建 Node.js/Node-webkit 插件时通过 binding.gyp 将 .cpp 文件编译为 Objective-C++

C - 从 ‘void*’ 到 ‘void (*)()’ 的无效转换

使用自定义类类型作为键的 C++ unordered_map

c++ - g++ 选项显示哪些类是从模板创建的

c++ - 如何在一个 catch block 中捕获所有类型的异常?

c++ - 内核调用产生错误 "error: a host function call cannot be configured"。调用有什么问题?

gcc - 如何使用 -DN 标志在 g++ 编译期间传递值

c++ - undefined symbol 体系结构 x86_64 的 undefined symbol : "_kCFAllocatorDefault"