c++ - 在函数范围外的 header 中使用 UDL

标签 c++ namespaces c++17 user-defined-literals

<分区>

如果我们想使用一些 UDL,我们需要使用相应的命名空间:

auto foo()
{
   using namespace std::literals::chrono_literals;

   std::chrono::milliseconds interval = 1s;
}

这很好,因为引入的命名空间已本地化到函数。

但我还没有找到在函数范围之外使用它们(例如类内初始化程序或函数默认参数)而不污染封闭命名空间的解决方案:

// this is a header

namespace my_ns
{

// I would like to avoid this:
// using namespace std::literals::chrono_literals;

struct Foo
{
   // can't have a using directive at class scope:
   // using namespace std::literals::chrono_literals;


   // I want to do this
   std::chrono::milliseconds interval = 1s;

   // I want to pretty pretty pretty please do this:
   Foo(std::chrono:milliseconds interval = 1s) : interval{interval} {}
};
}

在这里使用 UDL 有更好的方法吗?

最佳答案

这个怎么样?

namespace my_ns {
  namespace _ {
    using namespace std::literals::chrono_literals;
    struct Foo {
      std::chrono::milliseconds interval = 1s;

      Foo(std::chrono:milliseconds interval = 1s) : interval{interval} {}
    };
  }

  using Foo = _::Foo;
}

关于c++ - 在函数范围外的 header 中使用 UDL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45445468/

相关文章:

C# 类型或命名空间预期混淆

xml - 错误 : XML validator says conetent not allowed in trailing section and other namespace issues?

c++ - 函数指针数组的类模板参数推导适用于 clang,但不适用于 gcc

c++ - 确保 char 指针始终指向相同的字符串文字

c++ - “CvLoadImage”未在此范围内声明

c++ - 获取连接元组类型;结合 result_of 和 tuple_cat

class - 在 Fortran 中将模块分解为多个文件

c++ - 为什么 std::iota 不是 constexpr?

c++ - Qt5:使用 QSortFilterProxyModel 时拖放

c++ - 使用接口(interface)作为共享指针参数