4

如果我们想使用一些 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?

4

2 回答 2

2

这个怎么样?

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;
}
于 2017-08-01T18:48:56.607 回答
0

您可以添加一个(私有)函数作为解决方法:

namespace my_ns
{

   struct Foo
    {
       std::chrono::milliseconds interval = one_second();

       Foo(std::chrono::milliseconds interval = one_second()) : interval{interval} {}
    private:
        static std::chrono::seconds one_second() {
            using namespace std::literals::chrono_literals;
            return 1s;
        }
    };
}
于 2017-08-01T23:28:15.930 回答