Using UDL in Outer Header Scope
If we want to use some UDL, we need to use the appropriate namespace:
auto foo()
{
using namespace std::literals::chrono_literals;
std::chrono::milliseconds interval = 1s;
}
that everything is correct and good, because the entered namespace is localized in the function.
But I haven't found a solution to use them outside of the function scope (like a class initializer or a function default argument) without polluting the surrounding namespace:
// 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} {}
};
}
Is there a better way to use UDL here?
+3
source to share
2 answers
You can add a (private) function as a job:
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;
}
};
}
0
source to share