繁体   English   中英

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

[英]How to initialize template member array from constructor parameter?

基本上我想要一个模板类,其数组的大小是模板参数,用于保存常量内容。

就像是:

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创建一个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);
}

不确定我是否完全理解这些问题。 这是你想要实现的目标吗?

#include <iostream>
#include <array>

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

int main() {
    auto sample = Baz<5>({1,2,3}); // size = 5, values = 1, 2, 3, 0, 0
    return 0;
}

摘要:

  1. 使用std::array而不是原始数组。
  2. 指定模板参数,例如: Baz<5>(...) 不推导出类模板参数。

您可以使用经典的C数组,但使用可变参数构造函数

#include <array>
#include <cstddef>
#include <iostream>

using namespace std;

template <size_t S> struct Foo {
    const int bar[S];
    const std::array<int, S> bar2;

    template <typename ... I>
       Foo (const I & ... i) : bar {i...}, bar2 {{i...}}
    {
      cout << "bar size is " << S << " == " <<
         (sizeof(bar)/sizeof(bar[0])) << " == " << bar2.size() << endl;
    }
};

int main()
 {
   Foo<3>  foo {1,2,3};

   auto  foo2 = Foo<4>{1,2,3,4};

   return 0;
 }

暂无
暂无

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

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