如何在头文件中使用用户定义的文字? [英] How to use a user defined literal in a header file?

查看:75
本文介绍了如何在头文件中使用用户定义的文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

现在我可以在另一个标头中使用运算符 SomeComponent.h

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

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

但是,我不想用<$ c $污染范围c>使用命名空间my_literals ,因为这将为所有包含 SomeComponent.h的 *。cpp 文件提供文字定义。

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.

如何避免这种情况? constexpr uint64_t timeout = my_literals :: 10_nanoseconds; 在g ++中给出在数字常量之前的期望非限定ID

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

推荐答案

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

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

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

(C ++ 11及更高版本)的替代方案:

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

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

namespace foo {

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

这篇关于如何在头文件中使用用户定义的文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆