c++ - 在编译时创建 N 个对象的最佳方式

标签 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

但是因为它在构造函数中,所以无论如何它都会在编译后生成它。所以我真的只是想知道我应该如何解决这个问题。如果有某种巧妙的递归技巧,我可以在编译时为我创建这些对象。

最佳答案

你可以使用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_;
};

关于c++ - 在编译时创建 N 个对象的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36061928/

相关文章:

c++ - 结构未完成排序

java - 小程序 - 如何让这段代码使用字符串而不是字符?

c++ - 获取参数包中的参数类型

c++ - 命令行应用程序的自定义 URL 方案

Javascript 数组包含值

c++ - 使用映射的迭代器混淆

c++ - 对模板类的引用不明确 (C++)

c++ - 如何用 "float (*fSqrt)(float)"替换 "std::function<float(float) fSqrt>"?

c++ - 获取元组元素类型的索引?

c++ - C/С++。为什么 volatile 上的简单整数加法可以转换为 gcc 和 clang 上的不同 asm 指令?