节俭生成结构的c++大括号初始化

C++ Brace Initialization for Thrift-Generated Structures

本文关键字:初始化 c++ 结构      更新时间:2023-10-16

我使用的是Thrift w/c++,它用下面的构造函数生成了许多结构:

struct ThriftColor
{
  ThriftColor(const ThriftColor&);
  ThriftColor& operator=(const ThriftColor&);
  ThriftColor() : color((ZColor::type)0), duration(0) { }
  ZColor::type color;
  int32_t duration;
};

我还没能弄清楚如何用大括号初始化这个

我得到的错误是:
error: could not convert '{RED, 1000}' from '<brace-enclosed initializer list>' to 'ThriftColor'

或者当使用vector时:

error: could not convert '{{RED, 1000}, {GREEN, 2000}}' from '<brace-enclosed initializer list>' to 'std::vector<ThriftColor>'

结构的类似形式,作品:

struct TimedColor
{
    TimedColor(ZColor::type c, int d) : color(c), duration(d) {}
    ZColor::type color;
    int duration;
};

有没有办法让Thrift生成一个可以用大括号初始化的结构?和/或:是否有一种方法来初始化第一个结构?

提前感谢!

完整的示例:http://cpp.sh/3wgq

// Example program
#include <iostream>
#include <string>
#include <vector>
struct ZColor {
enum type {
    OFF,
    RED,
    GREEN,
    YELLOW,
    BLUE,
    MAGENTA,
    CYAN,
    WHITE
};
};

struct TimedColor
{
    TimedColor(ZColor::type c, int d) : color(c), duration(d) {}
    ZColor::type color;
    int duration;
};
struct ThriftColor
{
  ThriftColor(const ThriftColor&);
  ThriftColor& operator=(const ThriftColor&);
  ThriftColor() : color((ZColor::type)0), duration(0) { }
  ZColor::type color;
  int32_t duration;
};
template<typename T>  
void Dump( std::vector<T>& vec)
{
    for(typename std::vector<T>::iterator it = vec.begin(); it != vec.end(); it++)
    {
        std::cout << it->color << ":" << it->duration << std::endl;
    }
}
void TestFunction1()
{
    std::vector<TimedColor> vec;
    vec.push_back(TimedColor(ZColor::RED,1000));
    vec.push_back(TimedColor(ZColor::GREEN,2000));
    Dump(vec);    
}
void TestFunction2()
{
    std::vector<TimedColor> vec = { { ZColor::RED, 1000 }, { ZColor::GREEN, 2000 } };
    Dump(vec);    
}
void TestFunction3()
{
    // fails
    ThriftColor tc =  { ZColor::RED, 1000 };
    std::vector<ThriftColor> vec = { { ZColor::RED, 1000 }, { ZColor::GREEN, 2000 } };
    Dump(vec);    
}
int main()
{
  TestFunction1();
  TestFunction2();
  TestFunction3();
}

如果ThriftColor没有两个参数的构造函数,那么两个参数的初始化列表是无用的。

不能为此添加合适的构造函数

ThriftColor(ZColor::type color, int32_t duration) : color(color), duration(duration) {};

(或者有一些自动生成将消除它?)我对Thrift不太了解

事实证明,目前还不可能生成可以用Thrift进行括号初始化的复杂结构。进一步考虑一下,这可能是一件好事,因为Thrift生成了设置结构体成员的方法,这些方法跟踪是否设置了可选字段。例如,Thrift可能生成如下内容:

void ThriftColor::__set_duration(const int32_t val) {
  this->duration = val;
__isset.duration = true;
}

从大括号初始化中生成一个能够正确设置内部__isset结构的重要结构体是相当复杂的。

最后,我创建了一个辅助函数,它为我初始化我的ThriftColor向量,并使用它们来构建ThriftObject。