简体   繁体   English

如何使用外部链接在名称空间范围内定义常量double?

[英]How to define a constant double at namespace scope with external linkage?

I am trying to create a namespace-scope constant with external linkage 我正在尝试创建具有外部链接命名空间范围常量

// in some include file:

namespace foo 
{
    constexpr double bar() { return 1.23456; } // internal linkage
    constexpr double baz = 1.23456;            // internal linkage
    const double bing = 1.23456;               // internal linkage
}

Is this even possible? 这有可能吗?

Yes, and no ; 是的,没有 you can use extern : 您可以使用extern

[C++11: 3.5/3]: A name having namespace scope (3.3.6) has internal linkage if it is the name of [C++11: 3.5/3]: 具有名称空间范围 (3.3.6) 的名称如果具有以下名称,则具有内部链接:

  • a variable, function or function template that is explicitly declared static ; 明确声明为static的变量,函数或函数模板; or, 要么,
  • a variable that is explicitly declared const or constexpr and neither explicitly declared extern nor previously declared to have external linkage ; 一个显式声明为 constconstexpr 的变量, 既不显式声明extern也不先前声明不具有外部连接 ; or 要么
  • a data member of an anonymous union. 匿名联合的数据成员。

So: 所以:

namespace foo 
{
    extern constexpr double bar() { return 1.23456; }
    extern constexpr double baz = 1.23456;
}

In your other translation unit, you should now be able to declare the function's name and refer to it: 现在,在另一个翻译单元中,您应该能够声明该函数的名称并引用它:

#include <iostream>

namespace foo
{
   extern constexpr double bar();
}

int main()
{
   std::cout << foo::bar() << '\n';
}

However, the rules for constexpr variables state that you cannot have a declaration that is not also a definition : 但是, constexpr 变量的规则指出您不能有一个既不是定义的声明

[C++11: 7.1.5/9]: A constexpr specifier used in an object declaration declares the object as const . [C++11: 7.1.5/9]:在对象声明中使用的constexpr说明符将对象声明为const Such an object shall have literal type and shall be initialized. 这样的对象应具有文字类型并应进行初始化。 [..] [..]

So, you cannot take the same approach with baz . 因此,您不能对baz采用相同的方法。

constexpr for functions implies inline , which implies external linkage. 函数的constexpr意味着inline ,这意味着外部链接。 So you already have what you want for bar . 这样您已经拥有了想要的东西bar As for baz and bing , you can also declare them inline in C++17. 至于bazbing ,您还可以在C ++ 17中内联声明它们。

See also https://stackoverflow.com/a/4193698/261217 另请参阅https://stackoverflow.com/a/4193698/261217

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM