我一直在努力初始化包含联合结构成员的数组。假设我在 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}} };
}