2

它适用于struct RS : public JV<T,1>但不适用于struct RS : public JV<T,2>.

error: could not convert ‘{(0, j), (0, j)}’ from ‘&lt;brace-enclosed initializer list>’ to ‘WJ<float>’

我必须超载operator,()吗?代码:

#include<iostream>

struct B {};

template <std::size_t... Is>
struct indices {};

template <std::size_t N, std::size_t... Is>
struct build_indices
  : build_indices<N-1, N-1, Is...> {};

template <std::size_t... Is>
struct build_indices<0, Is...> : indices<Is...> {};

template<class T,int N>
struct JV {

  JV(B& j) : JV(j, build_indices<N>{}) {}
  template<std::size_t... Is>
  JV(B& j, indices<Is...>) : jit(j), F{{(void(Is),j)...}} {}

  B& jit;
  T F[N];
};

template<class T>
struct RS : public JV<T,2>
{
  RS(B& j): JV<T,2>(j) {}
};

template<class T>
struct WJ
{
  WJ(B& j) {
    std::cout << "WJ::WJ(B&)\n";
  }
};

int main() {
  B j;
  RS<WJ<float> > b2(j);
}
4

3 回答 3

4

{}如果要使用普通数组,则需要删除多余的部分F{(void(Is),j)...}。或者改成std::array<T, N> F你说的。

但是,普通数组仅{}用于初始化,并且std::array是包含数组的聚合,因此它使用双括号。

请参阅将 std::array 与初始化列表一起使用以获得更好的解释。

于 2012-10-12T10:43:25.350 回答
2

你的问题是额外的一对{}牙套。改变

  JV(B& j, indices<Is...>) : jit(j), F{{(void(Is),j)...}} {}

  JV(B& j, indices<Is...>) : jit(j), F{(void(Is),j)...} {}

它工作正常。

它使用的原因std::array包含实际数组array的聚合:

// from 23.3.2.1 [array.overview]
namespace std {
  template<typename T, int N>
  struct array {
...
    T elems[N];    // exposition only

因此,要初始化,与初始化实际数组array相比,需要额外的一对大括号。gcc 允许您省略额外的大括号,但抱怨:

  std::array<int, 3>{1, 2, 3};

警告:'std::array::value_type [3] {aka int [3]}' [-Wmissing-braces] 的初始化器周围缺少大括号

于 2012-10-12T10:45:26.060 回答
1

更换

 T F[N];

 std::array<T,N> F;

成功了!它似乎std::array可以做的不仅仅是 C 数组。

于 2012-10-12T10:41:10.887 回答