在函数范围之外的标头中使用 UDL

Using UDL in header outside function scope

本文关键字:UDL 函数 范围      更新时间:2023-10-16

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

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

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;
}
};
}