【问题标题】:could not convert from <brace-enclosed initializer list>无法从 <brace-enclosed initializer list> 转换
【发布时间】:2012-10-12 10:24:50
【问题描述】:

它适用于struct RS : public JV&lt;T,1&gt;,但不适用于struct RS : public JV&lt;T,2&gt;

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);
}

【问题讨论】:

    标签: c++ templates c++11


    【解决方案1】:

    如果要使用普通数组F{(void(Is),j)...},则需要删除多余的{}。或者像你说的那样把它改成std::array&lt;T, N&gt; F

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

    请参阅Using std::array with initialization lists 以获得更好的解释。

    【讨论】:

      【解决方案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] 的初始化器周围缺少大括号

      【讨论】:

      • 没关系,看起来它们只能以T x = { a };的形式省略。
      【解决方案3】:

      替换

       T F[N];
      

       std::array<T,N> F;
      

      成功了!看来std::array 可以做的不仅仅是 C 数组。

      【讨论】:

      • std::array 不一定能比 C 风格的数组做更多的事情,只是初始化的行为不同。 C 风格只需要一对大括号,而 std::array 是一个聚合(因此即使在 C++03 中也允许 {...} 初始化)。第二对大括号用于内部 C 样式数组成员。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 2013-01-13
      • 1970-01-01
      • 2023-02-11
      相关资源
      最近更新 更多