gpt4 book ai didi

c++ - 所有 constexpr 变量都隐式内联吗?

转载 作者:可可西里 更新时间:2023-11-01 18:24:18 24 4
gpt4 key购买 nike

我在玩弄自动模板参数,令我惊讶的是这段代码没有编译:

constexpr auto bar = 2;

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

int main() {
Foo<bar> b;
b();
}

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'

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

constexpr inline auto bar = 2;

我认为 constexpr 变量是隐式内联。另外,这对我的变量 bar 的链接有何影响?

最佳答案

Are all constexpr variable implicitly inline?

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

Also, how does that affect the linkage of my variable bar?

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

关于c++ - 所有 constexpr 变量都隐式内联吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49913011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com