是否可以根据整数模板参数构造成员数组的元素?

rit*_*ter 5 c++ templates c++11

假设:

template<class T,int N>
struct A {
  A(): /* here */ {}

  T F[N];
};
Run Code Online (Sandbox Code Playgroud)

我需要F[]构造的元素{0,1,2,...,N-1}.如果可能的话,我想避免递归定义的模板结构,定义最后一个级别,template<class T> struct A<T,0>并做一些复杂的模板技巧.C++ 11初始化列表可以帮助吗?

与使用值列表的类似模板数组初始化类似,但它不构造具有递增值的元素.它稍后在运行时循环中设置它.

Luc*_*ton 2

假设某种索引解决方案可用:

A(): A(make_indices<N>()) {}

// really a private constructor
template<int... Indices>
explicit A(indices<Indices...>)
    // Can be an arbitrary expression or computation, too, like
    // (Indices + 3)...
    : F {{ Indices... }}
{}
Run Code Online (Sandbox Code Playgroud)

如果您的编译器不支持委托构造函数,一种选择是切换到std::array<T, N>并使用返回初始化数组的私有静态帮助器,这样默认构造函数将变为:

A(): F(helper(make_indices<N>())) {}
Run Code Online (Sandbox Code Playgroud)

这当然会产生额外的(移动)构造。