简体   繁体   English

在标头中声明符号常量而不进行初始化?

[英]Declaring symbolic constants in header without initializing?

It is common practice to define symbolic constants in a header file: 通常在头文件中定义符号常量:

#define T_FOO 1
#define T_BAR 2

Ugly. 丑陋。

static const int T_FOO = 1;
static const int T_BAR = 2;

Better, since not preprocessor. 更好,因为不是预处理器。

enum
{
    T_FOO = 1,
    T_BAR
} T_Type;

Better still, since T_Type carries information of purpose, and the compiler can do additional checks (eg if all cases are handled in a switch ). 更好的是,由于T_Type带有目的信息,并且编译器可以执行其他检查(例如,是否所有情况都在switch中处理)。

There's probably half a dozen more variants. 大概还有六种变体。 One thing though... they all disclose numerical values to the client. 不过,有一件事……它们都向客户披露数值。 I'd like to keep those values hidden, simply because they shouldn't matter. 我想将这些值隐藏起来,只是因为它们无关紧要。 But the one way I could think of... 但是我想到的一种方式

typedef int T_Type;

// defined elsewhere
extern const T_Type T_FOO;
extern const T_Type T_BAR;

... does not work for eg case statements (as T_FOO and T_BAR are constants, but not a compile-time constant expressions). ... 不适用于例如case语句(因为T_FOOT_BAR是常量,但不是编译时常量表达式)。

Is there a way to have it all? 没有办法把它呢?

  • Declaring symbolic constants in a header without disclosing numerical values, 在标头中声明符号常量而不公开数值,
  • but useable as constant expressions eg in switch statements? 但可用作常量表达式,例如在switch语句中?

My level of understanding says "no", but I know that I don't know everything. 我的理解水平说“不”,但是我知道我并不了解所有事情。 ;-) ;-)

To be usable in as switch statement labels the values have to be seen by the compiler earlier in the source of this translation unit. 为了可用作switch语句标签,编译器必须早些时候在此转换单元的源代码中看到这些值。

So essentially, no , you can't declare symbolic constants without disclosing their values, and use them as labels in a switch . 因此,从本质上讲, ,您不能在不公开符号常量的情况下声明它们,并将其用作switch标签。

However, you can use an if - else construction. 但是,您可以使用if - else结构。

您可以将映射到T_Type的方法/函数指针保存在某个地方,但是,是的,这仅仅是出于问题的解决,因此不值得首先创建-硬编码逻辑只能与硬编码值一起使用。

Your typedef declaration was wrong. 您的typedef声明错误。 What about this one? 这个如何?

typedef int T_Type;

// defined elsewhere

extern const T_Type T_FOO;
extern const T_Type T_BAR;

// elsewhere defined as, say
const T_Type T_FOO = 1; 
const T_Type T_BAR = 2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM