我需要根据提供的“定义”包含不同数量的对象 并具有不同的构造函数参数
inline static std::array<A::Output, NUM_OUTPUTS> s_Outputs =
{
#if NUM_OUTPUTS > 0
A::Output{0}
#endif
#if NUM_OUTPUTS > 1
, A::Output{1}
#endif
#if NUM_OUTPUTS > 2
, A::Output{2}
#endif
};
好吧,根据 NUM_OUTPUTS
应该创建相应数量的对象。每个对象都有一个索引,第一个是“0
”,每个下一个是“+1
”。
有没有办法做得更好?可能是在此类声明或其他任何内容中推出宏。
最佳答案
使用 std::make_index_sequence
和一个 variable template你可以做到。
#include <utility> // std::integer_sequence
template <std::size_t... I>
constexpr auto makeArray(std::index_sequence<I...>)
{
return std::array<A::Output, sizeof...(I)>{I...};
}
template<std::size_t NUM_OUTPUTS>
constexpr static std::array<A::Output, NUM_OUTPUTS> s_Outputs = makeArray(std::make_index_sequence<NUM_OUTPUTS>{});
现在你可以
constexpr auto arr1 = s_Outputs<1>; // 0
constexpr auto arr2 = s_Outputs<2>; // 0 1
constexpr auto arr3 = s_Outputs<3>; // 0 1 2
请注意,上述解决方案需要 c++14编译器支持。
关于c++ - 如何在编译时在初始化列表中包含不同数量的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63792255/