使用静态const结构对相关的类常量进行分组(C ++ 11) [英] Using static const structs to group related class constants (C++11)

查看:105
本文介绍了使用静态const结构对相关的类常量进行分组(C ++ 11)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下(A)的(缺点)有哪些:

What are the (dis)advantages of using the following (A):

// .h
class SomeClass
{
    static const struct ConstantGroup
    {
        int a = 1;
        string b = "b";
        // ... etc.
    } CONSTANT;
};
// .cpp
const SomeClass::ConstantGroup SomeClass::CONSTANT;

对(B):

// .h
class SomeClass
{
    static const int A;
    static const string B;
    // .. etc.
};
// .cpp
const int SomeClass::A = 1;
const string SomeClass::B = "b";

...对于某些组相关的静态类常量?假定不涉及模板,并且常量包含简单类型(POD或字符串).

...for some group(s) of related static class constants? Assume no templates are involved and that the constants contain simple types (POD or strings).

到目前为止,我看到以下有利于(A)的优点:

So far I see the following advantages in favor of (A):

  • 相关常量可以作为一个组传递.正如评论中指出的那样,通常不希望这样做.
  • 鉴于常量经常一起访问,我们可以在需要时为结构创建简写形式以提高可读性,即: static const auto&SHORTHAND = SomeClass :: LONG_NAME_FOR_CONSTANTS;
  • Related constants can be passed around as a group As was pointed out in the comments, this is not generally desired.
  • Given that the constants are often accessed together, we can create shorthands for the structure to improve readability when needed, i.e.: static const auto & SHORTHAND = SomeClass::LONG_NAME_FOR_CONSTANTS;

使用此模式时有哪些缺点,陷阱或其他注意事项?

What are the disadvantages, gotcha's, or other things to keep in mind when using this pattern?

推荐答案

(A)可能很难通过从最终可执行文件中删除不必要的变量来进行优化.

(A) might be harder to optimize by removing unnecessary variables from the final executable.

如果要对常量进行分组,请考虑为此目的使用命名空间.

If you want to group constants, then consider using a namespace for that purpose.

namespace ConstantGroup
{
    constexpr int a = 1;

    // Here best solution might depend on usage and c++ version
    const std::string b;    
}

将常量作为一个组进行传递实际上没有多大意义.如果某些内容确实是常量,那么您需要一个定义并始终使用它.

Passing constants as a group really does not make much sense. If something is really constant, then you need a single definition and always use it.

如果常量非常特定于一个类,则使其成为该类的(静态)成员.

Also if the constant is very specific to one class, then make it a (static) member of that class.

这篇关于使用静态const结构对相关的类常量进行分组(C ++ 11)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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