最近遇到了一个奇怪的编译问题:
struct Row
{
const char* rowName;
uint32_t rowNum;
bool isInverted = false;
};
std::vector<Row> vecRows;
vecRows.push_back(Row{ "first row", 20 });
vecRows.push_back(Row{ "second row", 30 });
vecRows.push_back(Row{ "third row", 55, true });
这段代码我在Windows、Mac上编译都没有问题,但是在Ubuntu下编译却遇到了问题:
candidate expects 0 arguments, 2 provided
candidate expects 1 argument, 2 provided
candidate expects 0 arguments, 3 provided
candidate expects 1 argument, 3 provided
网上搜索发现一个类似问题(braced init with default values),原来这种初始化方式叫作聚合初始化(aggregate initialization),这段代码在C++11下是不合法的,但是在C++14下是合法的。在C++11下,给“isInverted”提供默认值会导致花括号的初始化方式变得无效。
如果要想在C++11下让这段代码可以工作,有两种方式:
- 不要给“isInverted”提供默认值
struct Row
{
const char* rowName;
uint32_t rowNum;
bool isInverted;
};
std::vector<Row> vecRows;
vecRows.push_back(Row{ "first row", 20, false });
vecRows.push_back(Row{ "second row", 30, false });
vecRows.push_back(Row{ "third row", 55, true });
- 给这个结构体提供一个构造函数
struct Row
{
Row(const char* _rowName, uint32_t _rowNum, bool _isInverted = false)
: rowName(_rowName)
, rowNum(_rowNum)
, isInverted(_isInverted)
{}
const char* rowName;
uint32_t rowNum;
bool isInverted;
};
std::vector<Row> vecRows;
vecRows.emplace_back("first row", 20);
vecRows.emplace_back("second row", 30);
vecRows.emplace_back("third row", 55, true);