c++ - 如何在编译时在初始化列表中包含不同数量的对象?

标签 c++ templates macros initialization compile-time

我需要根据提供的“定义”包含不同数量的对象 并具有不同的构造函数参数

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

( See a Demo Online )

请注意,上述解决方案需要 编译器支持。

关于c++ - 如何在编译时在初始化列表中包含不同数量的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63792255/

相关文章:

找不到 Scala : value macro

c++ - SFML 检测假操纵杆

c++ - 基类和派生类中类成员变量的初始化

c++ - 私有(private)数据类型和成员函数

c++ - 推荐哪本STL引用书?

c++ - 我无法直接将模板函数传递给 std::apply 但我可以通过 lambda

python - Django 在每个页面显示一个 View

c++ - C++中#define的合适使用场景是什么?

macros - 检查标识符是否在宏扩展时按词法绑定(bind)?

css - Ember.js 模板和全高(包括 JS bin 示例)