所有constexpr变量是否隐式内联?

Gui*_*cot 7 c++ linkage c++17 inline-variable

我正在玩自动模板参数,我很惊讶这段代码没有编译:

constexpr auto bar = 2;

template<auto& T>
struct Foo {
    auto operator()() const { return T; }
};

int main() {
    Foo<bar> b;
    b();
}
Run Code Online (Sandbox Code Playgroud)

Visual Studio 15.7(预览4)吐出这些错误:

error C2970: 'Foo': template parameter 'T': 'bar': an expression involving objects with internal linkage cannot be used as a non-type argument
 note: see declaration of 'Foo'
 note: see declaration of 'bar'
error C2440: 'specialization': cannot convert from 'int' to 'int &'
 note: see reference to class template instantiation 'Foo<0>' being compiled
error C2973: 'Foo': invalid template argument 'int'
 note: see declaration of 'Foo'
Run Code Online (Sandbox Code Playgroud)

然后,添加后inline,错误就消失了!

constexpr inline auto bar = 2;
Run Code Online (Sandbox Code Playgroud)

我认为constexpr变量是含蓄的inline.另外,这如何影响我的变量的链接bar?

cpp*_*ner 13

所有constexpr变量是否隐式内联?

不可以.只有constexpr函数和constexpr静态数据成员是隐式内联的([dcl.constexpr]/1).

另外,这如何影响我的变量栏的链接?

constexpr变量是const([dcl.constexpr]/9).const未显式声明的非内联变量extern具有内部链接([basic.link]/3).

  • @GuillaumeRacicot,你有权感到困惑,原始标准论文本身就是错误的,因为它没有提到这种区别。http://open-std.org/JTC1/SC22/WG21/docs/papers/2016/p0386r0.pdf (3认同)
  • 啊! 这是我感到困惑的地方,隐式内联仅适用于静态数据成员constexpr,而不是所有constexpr变量。 (2认同)