Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 285
Steve Lorimer Avatar asked Jan 31 '13 00:01

Steve Lorimer


1 Answers

Yes, and no; you can use extern:

[C++11: 3.5/3]: A name having namespace scope (3.3.6) has internal linkage if it is the name of

  • a variable, function or function template that is explicitly declared static; or,
  • a variable that is explicitly declared const or constexpr and neither explicitly declared extern nor previously declared to have external linkage; 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:

[C++11: 7.1.5/9]: A constexpr specifier used in an object declaration declares the object as const. Such an object shall have literal type and shall be initialized. [..]

So, you cannot take the same approach with baz.

like image 148
Lightness Races in Orbit Avatar answered Oct 19 '22 12:10

Lightness Races in Orbit