简体   繁体   English

C++ 使用嵌套联合定义结构时需要一个表达式

[英]C++ Expected an expression when defining struct with nested union

I have a struct with a nested union in c++, as follows:我在 C++ 中有一个带有嵌套联合的结构,如下所示:

typedef enum {            
  VAL_BOOL,               
  VAL_NIL, 
  VAL_NUMBER,             
} ValueType; 

typedef struct {  
  ValueType type; 
  union {         
    bool boolean; 
    double number;
  } as; 
} Value; 

I am trying to build a #define function to make initializing these values more readable, and this is what I have thus far, but it doesn't compile:我正在尝试构建一个#define函数以使初始化这些值更具可读性,这是我迄今为止所拥有的,但它无法编译:

#define NUMBER_VAL(value) ((Value){ VAL_NUMBER, { .number = value } })

The above implementation generates the following error at compile-time when the NUMBER_VAL(val) is used: expected an expression当使用NUMBER_VAL(val)时,上述实现在编译时生成以下错误: expected an expression

The goal here is to be able to define a Value by writing something like the following:这里的目标是能够通过编写如下内容来定义Value

double dub = 1.23;
Value val = NUMBER_VAL(dub);

or pass it to a function, like so:或将其传递给函数,如下所示:

void process_value(Value value);
...
double dub = 45.6; 
process_value(NUMBER_VAL(dub));

Is there some way to convert this #define -ition into an expression that would let me use it this way?有什么方法可以将这个#define -ition转换为一个表达式,让我以这种方式使用它? Or is my only option here to write a proper function to build these structs for me?或者我唯一的选择是编写一个适当的函数来为我构建这些结构?


For the record, I know that the following would work, but I was hoping for something more succinct.为了记录,我知道以下内容会起作用,但我希望有更简洁的内容。

Value NUMBER_VAL(double value) {
    Value val;
    val.type = VAL_NUMBER;
    val.as.number = value;
    return val;
}

Live code .实时代码

In C++ unions can have constructors.在 C++ 中,联合可以有构造函数。 In your struct you can define constructor overloads to initialize the union member along with the union tag ie type .在您的struct您可以定义构造函数重载以初始化联合成员以及联合标记,即type

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

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