无法从<大括号括起来的初始值设定项列表转换>

could not convert from <brace-enclosed initializer list>

本文关键字:gt 列表 转换 起来 lt      更新时间:2023-10-16

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

error: could not convert ‘{(0, j), (0, j)}’ from ‘<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);
}

如果要使用纯数组F{(void(Is),j)...},则需要删除额外的{}。或者像你说的那样把它改成std::array<T, N> F

然而,普通数组只是使用 {} 进行初始化,std::array是一个包含数组的聚合,因此它使用双大括号。

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

您的问题是多了一对{}大括号。 改变

  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] 的初始值设定项周围缺少大括号

替换

 T F[N];

 std::array<T,N> F;

成功了!似乎std::array可以做的比 C 数组更多。