我需要根据提供的“定义”和不同的ctor参数包括不同数量的对象
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
和变量模板,您可以做。
#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编译器支持。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句