对于这段代码:
struct S
{
S(int m): m(m) {}
constexpr int f() const { return m; }
int m;
};
int main() { S s(1); }
它由 clang 3.6、3.7 和 3.8 使用 -std=c++14
编译,没有警告或错误。但在 g++ 5.x 中出现以下错误:
main.cpp:4:19: error: enclosing class of constexpr non-static member function 'int S::f() const' is not a literal type
constexpr int f() const { return m; }
^
main.cpp:1:8: note: 'S' is not literal because:
struct S
^
main.cpp:1:8: note: 'S' is not an aggregate, does not have a trivial default constructor, and has no constexpr constructor that is not a copy or move constructor
哪个编译器是正确的,为什么?
我查看了 C++14 [dcl.constexpr]/3 中的要求,它说对于 constexpr
函数“它的每个参数类型都应该是文字类型”,但是那个部分没有明确提及成员函数,也没有说明隐含的 *this
是否算作本子句的参数。
最佳答案
这是为 C++14 修复的核心缺陷
http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1684
Clang 已修补
https://groups.google.com/a/isocpp.org/forum/#!topic/std-discussion/6jM8M8FUs30
有一个 GCC 跟踪器,但看起来还没有人解决它
关于c++ - 具有非 constexpr 构造函数的 constexpr 非静态成员函数(gcc、clang 不同),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36489369/