在内联命名空间标题中隐藏私有常量 [英] Hiding private constants in an inline namespace header

查看:144
本文介绍了在内联命名空间标题中隐藏私有常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些内联函数包含在头文件中的命名空间中,目前不能将它们移动到cpp文件中。这些内联函数中的一些使用魔术常量,例如:

I have some inline functions contained within a namespace in a header file and am not currently in a position to move them into a cpp file. Some of these inline functions use magic constants, for example:

// Foo.h
namespace Foo
{
    const int BAR = 1234;

    inline void someFunc()
    {
        // Do something with BAR
    }
}

但是,我想让这些魔法常量私有 - 任何想法如何?我的第一个想法是使用匿名命名空间,因此:

However, I want to make these magic constants private - any ideas how? My first thought was to use an anonymous namespace thus:

// Foo.h
namespace Foo
{
    namespace
    {
        // 'private' constants here
        const int BAR = 1234;
    }

    inline void someFunc()
    {
        // Do something with BAR
    }
}

但是,这不起作用, Foo :: BAR 任何包含 Foo.h 的cpp文件?有没有办法这样做而不创建一个实现cpp文件?

However, this doesn't work and Foo::BAR is available to any cpp file that includes Foo.h? Is there a way to do this without creating an implementation cpp file?

推荐答案

匿名命名空间工作的翻译

您可以考虑将它们移动到详细命名空间中,以向用户表示他们是内部细节:

You can't, anonymous namespaces work for the translation unit they are defined in (or included into in your case).
You could consider moving them into a detail namespace to signal to the user that they are internal details:

namespace foo {
    namespace detail {
        int magic = 42;
    }

    // ... use detail::magic
}

这篇关于在内联命名空间标题中隐藏私有常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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