如何在初始化时将不同数量的对象包括在初始化列表中? [英] How to include different number of objects at compile time in the initializer list?
本文介绍了如何在初始化时将不同数量的对象包括在初始化列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要根据提供的定义"添加不同数量的对象并具有不同的ctor参数
I need to include a different number of objects depending on the provided 'define' and with different ctor parameters
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
'.
Well depending on NUM_OUTPUTS
respective number of the object should be created. Each object has an index, first is '0
' and every next is '+1
'.
有没有一种更好的方法?可能是宏会在此类声明或其他内容中推出.
Is there a way to do it more nicely? Probably macros to roll out in such declarations or anything else.
推荐答案
使用 <代码> 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
(在线观看演示)
(See a Demo Online)
请注意,上述解决方案需要 c ++ 14 编译器支持.
Note that, the above solution required c++14 compiler support.
这篇关于如何在初始化时将不同数量的对象包括在初始化列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文