How to define a constant double in an externally linked namespace?

I am trying to create a namespace-scope constant with external link

// 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 it possible?

+5


source to share


2 answers


Yes and no ; you can use extern

:

[C++11: 3.5/3]:

A namespaced name (3.3.6) has an internal linkage if that name

  • a variable, function, or function template that is explicitly declared static

    ; or,
  • variable that is explicitly declared const

    , or , and not explicitly declared , as previously announced, that it has an external snap >; or constexpr

    extern

  • data member of the anonymous association.

So:

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

      

In your other translation unit, you should now declare the function name and refer to it:



#include <iostream>

namespace foo
{
   extern constexpr double bar();
}

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

      

However, the rules for variables constexpr

indicate that you cannot have a declaration that is also not a definition :

[C++11: 7.1.5/9]:

A qualifier constexpr

used in an object declaration declares the object as const

. Such an object must be of a literal type and must be initialized. [..]

So, you cannot use the same approach with baz

.

+10


source


constexpr

for functions implies inline

that implies external communication. So, you already have what you want for bar

. As for baz

and bing

, you can also declare them inline in C ++ 17.



See also fooobar.com/questions/341188 / ...

0


source







All Articles