繁体   English   中英

无法从转换<brace-enclosed initializer list>

[英]could not convert from <brace-enclosed initializer list>

它适用于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)...}则需要删除多余的{} 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数组还要多。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM