Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to user defined literal operator inside a namespace?

Consider the following:

#include <iostream>

namespace X
{
    void operator ""_test(unsigned long long x)
    {
        std::cout << x;
    }
}

int main()
{
    using namespace X;
    10_test;
    // 10_X::test; /* doesn't work */
}

I can refer to the user defined literal operator inside the namespace X by an explicit using namespace X;. Is there any way of referring to the literal operator without explicitly including the namespace? I tried the

10_X::test;

but of course doesn't work as the parser believes X refers to the name of the operator.

X::operator ""_test(10)

works but it's clumsy.

like image 515
vsoftco Avatar asked Mar 01 '18 16:03

vsoftco


People also ask

What is a user-defined literal?

In source code, any literal, whether user-defined or not, is essentially a sequence of alphanumeric characters, such as 101 , or 54.7 , or "hello" or true . The compiler interprets the sequence as an integer, float, const char* string, and so on.

What is user-defined literals in C++?

Similarly, User-Defined Literals (UDL) provides literals for a variety of built-in types that are limited to integer, character, floating-point, string, boolean, and pointer. In simple terms, they combine values with units. Examples of literal for built-in types: // Examples of classical literals for built-in types.


1 Answers

#include <iostream>

namespace X {
  inline namespace literals {
    void operator ""_test(unsigned long long x) {
      std::cout << x;
    }
  }
}

int main() {
  {
    using namespace X::literals;
    10_test;
  }
  {
    using X::operator""_test;
    10_test;
  }
}

_test is both in X and X::literals. This permits people to using namespace X::literals; without pulling in everything from X, yet within X _test is also available.

Importing an individual literal is a bit annoying.

std does this with both std::chrono and std::literals and std::chrono::literals. inline namespaces let you define subsections of your namespace that you think people would want to import as a block without getting the rest of it.

like image 82
Yakk - Adam Nevraumont Avatar answered Oct 04 '22 22:10

Yakk - Adam Nevraumont