是否所有constexpr变量都隐式内联? [英] Are all constexpr variable implicitly inline?
问题描述
我在玩自动模板参数,而令我惊讶的是这段代码没有编译:
I was playing around with auto template parameters and I was surprised that this code didn't compiled:
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)吐出这些错误:
Visual Studio 15.7 (preview 4) spit out these errors:
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
后,错误消失了!
Then, after adding inline
, the error got away!
constexpr inline auto bar = 2;
我认为constexpr
变量是隐式inline
.另外,这如何影响变量bar
的链接?
I thought constexpr
variables were implicitly inline
. Also, how does that affect the linkage of my variable bar
?
推荐答案
所有constexpr变量是否隐式内联?
Are all constexpr variable implicitly inline?
不.仅constexpr函数和constexpr静态数据成员是隐式内联的( [dcl. constexpr]/1 ).
No. Only constexpr functions and constexpr static data members are implicitly inline ([dcl.constexpr]/1).
还有,这如何影响我的变量栏的链接?
Also, how does that affect the linkage of my variable bar?
constexpr变量为const
( [dcl.constexpr ]/9 ).未显式声明为extern
的非内联const
变量具有内部链接( [basic.link]/3 ).
A constexpr variable is const
([dcl.constexpr]/9). A non-inline const
variable that is not explicitly declared extern
has internal linkage ([basic.link]/3).
这篇关于是否所有constexpr变量都隐式内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!