简体   繁体   English

如何在命名空间范围内转发声明constexpr对象?

[英]How do I forward-declare a constexpr object at namespace scope?

On clang (trunk) I can forward declare an object that will later be defined with constexpr as follows: 在clang(trunk)上我可以转发声明一个稍后用constexpr定义的对象,如下所示:

// Fwd-declarations
struct S;
extern const S s;

// (... later) definitions
struct S {};
constexpr S s {};

Gcc 4.8 doesn't like this, telling me the forward-declaration and the definition differ in constexpr -ness. Gcc 4.8不喜欢这样,告诉我前向声明和constexpr -ness的定义不同。 Is gcc speaking truth, or is this just a gcc bug? 是gcc说实话,还是这只是一个gcc bug?

I can't find any language in my copy of the C++11 standard that explicitly forbids constexpr -ness from mis-matching between a declaration and a definition, but I do see language explicitly forbidding constexpr from being used with extern (section 7.1.5), and I also see language requiring the initializer for a class-level static constexpr variable to be in the class. 我在C ++ 11标准的副本中找不到任何语言明确禁止constexpr -ness从声明和定义之间的错误匹配,但我确实看到语言明确禁止constexprextern (第7.1节) .5),我还看到语言要求类级static constexpr变量的初始化程序在类中。 Also, since the utility of constexpr is significantly reduced when the definition of the variable or its type is unavailable, I think it's likely the intent is that constexpr variables must be defined (or, for static class members, initialized) when they are declared. 此外,由于当变量或其类型的定义不可用时, constexpr的效用显着降低,我认为可能的意图是必须在声明变量时定义constexpr变量(或者,对于static类成员,初始化)。

As a work-around, perhaps you could provide an extern alias for the variable. 作为解决方法,也许您可​​以为变量提供extern别名。 This would allow you to take its address, and that's the only thing I can think of that a forward-declaration would allow. 这将允许您获取其地址,这是我能够想到的前瞻性声明允许的唯一内容。 For example: 例如:

// .hpp file:
struct C;
extern C const &c;

// .cpp file:
struct C {
    constexpr C() { }
};
constexpr C cc;
C const &c = cc;

Side note: I know that in C++14, they revisited/are revisiting constexpr , so it's possible that it works in Clang because it's implementing some draft spec of C++14. 旁注:我知道在C ++ 14中,他们重新访问/正在重新访问constexpr ,因此它可能在Clang中起作用,因为它正在实现C ++ 14的一些草案规范。

The real answer is that gcc is plain wrong, clang is right. 真正的答案是gcc是完全错误的,clang是对的。 The code above should compile, and it will in gcc 4.9. 上面的代码应该编译,它将在gcc 4.9中。 Or so says this bug report . 或者说这个错误报告

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM