如何在命名空间中引用用户定义的文字运算符? [英] How to refer to user defined literal operator inside a namespace?

查看:123
本文介绍了如何在命名空间中引用用户定义的文字运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下内容:

#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 */
}

我可以参考用户定义的文字运算符命名空间X 通过使用命名空间X; 的显式来实现。有什么方法可以在不显式包括名称空间的情况下引用文字运算符?我尝试了

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;

但由于解析器认为 X 是运算符的名称。

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

X::operator ""_test(10)

可以,但是很笨拙。

推荐答案

#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 都在 X X :: literals 中。这允许人们使用命名空间X :: literals; ,而不必提取 X 中的所有内容,而又将 X _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.

导入单个文字有点

std 都使用 std :: chrono std :: literals std :: chrono :: literals 内联命名空间允许您定义命名空间的子节,您认为人们希望将其作为块导入而没有得到其余部分。

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.

这篇关于如何在命名空间中引用用户定义的文字运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆