为什么非成员静态constexpr变量不隐式内联? [英] Why are non member static constexpr variables not implicitly inline?

查看:119
本文介绍了为什么非成员静态constexpr变量不隐式内联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 17中,我们获得了内联变量,并且我假设全局constexpr变量是隐式内联的。
但是显然,这仅适用于静态 member 变量。

In C++17 we got inline variables and I have assumed that global constexpr variables are implicitly inline. But apparently this is true only for static member variables.

这背后的逻辑/技术限制是什么?

What is the logic/technical limitation behind this?

来源:


声明为constexpr的静态成员变量(但不是名称空间范围的变量)隐式为内联变量。

A static member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.


推荐答案

此处的要点是 constexpr int x = 1; 在C ++ 14中具有命名空间范围的内部链接。

The point here is that constexpr int x = 1; at namespace scope has internal linkage in C++14.

如果隐式内联而不更改内部链接部分,则更改会无效,因为内部链接意味着无论如何都无法在其他翻译单元中定义它。它损害了可教学性,因为我们希望 inline constexpr int x = 1; 之类的东西默认获得外部链接(毕竟,整个内联点是允许相同变量,将在多个翻译单元中进行定义。)

If you make it implicitly inline without changing the internal linkage part, the change would have no effect, because the internal linkage means that it can't be defined in other translation units anyway. And it harms teachability, because we want things like inline constexpr int x = 1; to get external linkage by default (the whole point of inline, after all, is to permit the same variable to be defined in multiple translation units).

如果将其隐式内联到外部链接中,则会破坏现有代码:

If you make it implicitly inline with external linkage, then you break existing code:

// TU1
constexpr int x = 1;

// TU2
constexpr int x = 2;

此完全有效的C ++ 14会违反ODR。

This perfectly valid C++14 would become an ODR violation.

这篇关于为什么非成员静态constexpr变量不隐式内联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆