节俭生成结构的c++大括号初始化
C++ Brace Initialization for Thrift-Generated Structures
我使用的是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。
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 为什么在C++中首先初始化成员类
- 同时具有"聚合初始化"和"模板推导"
- 初始化具有非默认构造函数的std::数组项的更好方法
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 在C和C++中初始化结构中的数组
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 在函数内部的声明中初始化数组,并在外部使用它
- 继承:构造函数,初始化C++11中基类的类C数组成员