c++ - 如何从构造函数参数初始化模板成员数组?

标签 c++ arrays templates c++11 c++14

本质上我想要一个模板类,它有一个数组,其大小是一个模板参数,以保存不变的内容。

类似于:

template<size_t S> struct Foo {
    const int bar[S];
    Foo(const int(&par)[S]) : bar(par) {
        cout << "bar size is " << S << endl;
    }
};
auto foo = Foo({1,2,3});

我一直在搜索和修改,几乎有一个使用中间静态方法和使用 std::array 实现的解决方法:

template<size_t S> struct Baz {
  const array<int,S> qux;
  Baz(const array<int,S>&par) : qux(par) {
    cout << "size is " << S << endl;
  }
};
template<size_t S> Baz<S>
GetBaz(const array<int,S>&in) {
  return Baz<S>(in);
}

int main() {
  auto sample = GetBaz({1,2,3});
  return 0;
}

... 这已经是一些样板文件了,但 std::array 似乎仍然不是从初始化列表中构建的? :-(

prog.cpp: In function 'int main()':
prog.cpp:27:30: error: no matching function for call to 'GetBaz(<brace-enclosed initializer list>)'
  auto sample = GetBaz({1,2,3});

最佳答案

发布- DR1591内置数组边界现在可以从 braced-init-list 中推导出来,所以:

template<size_t S> struct Baz {
  const array<int,S> qux;
  Baz(const array<int,S>&par) : qux(par) {
    cout << "size is " << S << endl;
  }
  Baz(const int (&par)[S]) : qux(std::experimental::to_array(par)) {}
};

template<size_t S> Baz<S>
GetBaz(const int (&in)[S]) {
  return Baz<S>(in);
}

std::experimental::to_array从一个内置的创建一个 std::array。请参阅链接的 cppreference 页面以了解实现情况。

你可以一直使用内置数组,但它有点烦人:

template<size_t S> struct Baz {
  const int bar[S]; 

  template<size_t... Is>
  Baz(const int (&par)[S], std::index_sequence<Is...>)
      : bar { par[Is]... } {}

  Baz(const int (&par)[S]) : Baz(par, std::make_index_sequence<S>()) {}
};

template<size_t S> Baz<S>
GetBaz(const int (&in)[S]) {
  return Baz<S>(in);
}

关于c++ - 如何从构造函数参数初始化模板成员数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36233587/

相关文章:

c++ - 根据值c++从 map 中获取键

javascript - 迭代时修改数组

c++ - 当它是模板参数时默认成员变量指针

c++ - 如何制作适用于模板类的非模板全局函数?

c++ - 如何实现自动插入隐含占位符的 easy_bind() ? *带有成员指针*

c++ - Lambda 变量捕获

c++ - 如何在 C++ 中初始化需要参数的结构数组

c++ - 从字符串中修剪空格

c++ - 声明指向整数数组的指针 C++

c - 如何在c中的函数中手动输入数组?