Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a user defined literal in a header file? [duplicate]

I have defined the following user-defined literal in MyLiteral.h:

namespace my_literals {
    constexpr uint64_t operator"" _nanoseconds(unsigned long long int value) {
        return value*1000;
    }
}

Now I could use the operator in another header SomeComponent.h:

using namespace my_literals;
namespace foo {
    constexpr uint64_t timeout = 10_nanoseconds;
}

However, I don't want to pollute the scope by using namespace my_literals, because this would provide the literal definition to all *.cpp files which include SomeComponent.h.

How can I avoid this? constexpr uint64_t timeout = my_literals::10_nanoseconds; gives expected unqualified-id before numeric constant in g++.

like image 843
Alexander Avatar asked Jun 20 '18 07:06

Alexander


2 Answers

In C++17, with constexpr lambda, you may do:

namespace foo {
    constexpr uint64_t timeout = []{ using namespace my_literals; return 10_nanoseconds; }();
}

as alternative to (C++11 and higher):

namespace foo {
    constexpr uint64_t timeout = my_literals::operator""_nanoseconds(10);
}

or

namespace foo {

    namespace detail
    {
        using namespace my_literals;
        constexpr uint64_t timeout = 10_nanoseconds;
    }
    using detail::timeout;
}
like image 62
Jarod42 Avatar answered Nov 18 '22 18:11

Jarod42


You can get around this by calling the operator explicitly:

namespace foo {
    constexpr uint64_t timeout = my_literals::operator""_nanoseconds(10);
}
like image 8
DeiDei Avatar answered Nov 18 '22 18:11

DeiDei