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

走远了吗. 提交于 2019-12-01 15:12:47

问题


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.


回答1:


#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.



来源:https://stackoverflow.com/questions/49054477/how-to-refer-to-user-defined-literal-operator-inside-a-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!