How to access a custom 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 reference a custom literal operator internally namespace Xwith an explicit one using namespace X;. Is there a way to access a literal operator without explicitly including a namespace? I tried

10_X::test;

but, of course, it doesn’t work, because the parser considers that it Xrefers to the name of the operator.

X::operator ""_test(10)

It works, but it's awkward.

+4
source share
1 answer
#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;
  }
}

_testlocated in Xand X::literals. This allows people using namespace X::literals;not to drag out everything from X, but within, is X _testalso available.

Importing a single literal is a little annoying.

std std::chrono, std::literals std::chrono::literals. inline namespace , , , , .

+7

Source: https://habr.com/ru/post/1694304/


All Articles