C++ 如何在头文件中使用用户定义的文本?

C++ 如何在头文件中使用用户定义的文本?,c++,c++11,c++14,constexpr,user-defined-literals,C++,C++11,C++14,Constexpr,User Defined Literals,我在MyLiteral.h中定义了以下用户定义的文字: namespace my_literals { constexpr uint64_t operator"" _nanoseconds(unsigned long long int value) { return value*1000; } } using namespace my_literals; namespace foo { constexpr uint64_t timeout = 10_na

我在
MyLiteral.h
中定义了以下用户定义的文字:

namespace my_literals {
    constexpr uint64_t operator"" _nanoseconds(unsigned long long int value) {
        return value*1000;
    }
}
using namespace my_literals;
namespace foo {
    constexpr uint64_t timeout = 10_nanoseconds;
}
现在我可以在另一个标题中使用操作符
SomeComponent.h

namespace my_literals {
    constexpr uint64_t operator"" _nanoseconds(unsigned long long int value) {
        return value*1000;
    }
}
using namespace my_literals;
namespace foo {
    constexpr uint64_t timeout = 10_nanoseconds;
}
但是,我不想通过
使用名称空间my_literals
来污染范围,因为这将为所有
*.cpp
文件提供文本定义,其中包括
SomeComponent.h


我怎样才能避免这种情况
constexpr uint64\u t timeout=my\u literals::10\u纳秒
在g++中的数值常量之前给出预期的非限定id。

您可以通过显式调用运算符来解决此问题:

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

在C++17中,使用constexpr lambda可以执行以下操作:

namespace foo {
    constexpr uint64_t timeout = []{ using namespace my_literals; return 10_nanoseconds; }();
}
作为(C++11及更高版本)的替代方案:


您可以将
using
声明放在名称空间内(如果您不介意
foo::operator”“\u纳秒可用):


极其丑陋:)@kreuzerkrieg毫无疑问。不过,对于库代码来说,这很好。我可以确认这是有效的,并且包含了我的意图。然而,它显然很难看,不再是一个直观的文字。@Alexander顺便问一句,你为什么不使用
std::chrono
实用程序?@vsz我假设这是库代码,而
使用名称空间的
不应该泄露给用户。是的,我介意,原因如下:@Alexander有趣…对不起,我之所以重新打开,是因为重复的答案没有位于头文件中的约束,但事实证明,解决方案是相同的。我把它作为复制品重新关上了。
namespace foo {
    using namespace my_literals;
    constexpr uint64_t timeout = 10_nanoseconds;
}