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)吐出这些错误:
Run Code Online (Sandbox Code Playgroud)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;
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).