我一直在努力初始化包含联合结构成员的数组。
假设我在 C++ 中有以下声明
enum class FilterType { kLowPass, kAverage };
enum class FilterLowPassConfig {
k1kHzLowPass = 0,
k10kHzLowPass = 1,
k20kHzLowPass = 2,
k40kHzLowPass = 3
};
enum class FilterAverageConfig {
kWindowSize256 = 0,
kWindowSize128 = 1,
kWindowSize64 = 2,
kWindowSize32 = 3
};
union FilterConfig {
FilterLowPassConfig low_pass_config;
FilterAverageConfig average_config;
};
struct FilterSelect
{
FilterType filter_type;
FilterConfig filter_config;
};
现在我定义一个数组:
FilterSelect filter_select[2];
是否可以使用大括号括起来的初始化列表来初始化数组
filter_select
?
std::variant
代替 C 样式联合。
在现代 C++ 中,一般建议使用
std::variant
(请参阅更多信息此处),使用它您可以执行以下操作:
#include <variant>
enum class FilterType { kLowPass, kAverage };
enum class FilterLowPassConfig {
k1kHzLowPass = 0,
k10kHzLowPass = 1,
k20kHzLowPass = 2,
k40kHzLowPass = 3
};
enum class FilterAverageConfig {
kWindowSize256 = 0,
kWindowSize128 = 1,
kWindowSize64 = 2,
kWindowSize32 = 3
};
using FilterConfig = std::variant<FilterLowPassConfig, FilterAverageConfig>;
struct FilterSelect
{
FilterType filter_type;
FilterConfig filter_config;
};
int main()
{
[[maybe_unused]] FilterSelect filter_select[2] =
{ { FilterType::kLowPass, FilterLowPassConfig{FilterLowPassConfig::k1kHzLowPass}},
{ FilterType::kAverage, FilterAverageConfig{FilterAverageConfig::kWindowSize256}} };
}
std::array
代替 C 样式数组:
#include <array>
// ...
int main()
{
[[maybe_unused]] std::array<FilterSelect, 2> filter_select =
{ FilterSelect{FilterType::kLowPass, FilterLowPassConfig{FilterLowPassConfig::k10kHzLowPass}},
FilterSelect{FilterType::kLowPass, FilterLowPassConfig{FilterLowPassConfig::k10kHzLowPass}} };
}