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

gat*_*ich 2 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});
Run Code Online (Sandbox Code Playgroud)

我一直在寻找和修补,几乎有一个使用中间静态方法和使用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;
}
Run Code Online (Sandbox Code Playgroud)

...这已经是一些样板了,但是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});
Run Code Online (Sandbox Code Playgroud)

T.C*_*.C. 5

后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);
}
Run Code Online (Sandbox Code Playgroud)

std::experimental::to_arraystd::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);
}
Run Code Online (Sandbox Code Playgroud)