在编译时创建N个对象的最佳方法

时间:2016-03-17 13:26:24

标签: c++ arrays templates object

我想知道如何在编译时使用模板创建N个对象。或者这确实是一种很好的做法。

我有一个包含一些常量的头文件:

constexpr size_t N_TIMES = 3;
constexpr uint32_t MIN[N_TIMES] = {0,1,2};
constexpr uint32_t MAX[N_TIMES] = {1,2,3};

然后是一个包含模板的头文件,该模板将生成" N"次:

template <typename T>
class foo
{

public:

  foo(uint32_t min , uint32_t max) :
    min(min),
    max(max)
  {
    std::cout << "I was created with " << min << " " << max << std::endl;
  }

private:

  const uint32_t min;
  const uint32_t max;
};

我有点不确定的部分是我:

template <typename T>

class bar 
{
public:

  bar()
  {

    for(auto i = 0; i < N_TIMES; i ++)
          {
            foo_[i] = foo<T>(MIN[i], MAX[i]);
          }
  }
private:
  std::array<foo<T>, N_TIMES> foo_;
};

我目前收到错误:

cannot be assigned because its copy assignment operator is implicitly deleted

但是因为它在构造函数中,所以无论如何都会在编译之后生成它。所以我真的想知道我应该如何改变这一点。如果有某种聪明的递归技巧,我可以在编译时为我创建这些对象。

1 个答案:

答案 0 :(得分:1)

您可以使用std::index_sequence

namespace detail
{

    template <typename T, std::size_t N, std::size_t...Is>
    std::array<Foo<T>, N> make_foo_array(std::index_sequence<Is...>)
    {
        return {{Foo<T>(MIN[Is], MAX[Is])...}};    
    }

}

template <typename T, std::size_t N>
std::array<Foo<T>, N> make_foo_array()
{
    return detail::make_foo_array<T, N>(std::make_index_sequence<N>{});
}

然后

template <typename T>
class bar 
{
public:
    bar() : foo_(make_foo_array<T, N_TIMES>()) {}
private:
    std::array<foo<T>, N_TIMES> foo_;
};