【问题标题】:Populate an array of template pointers class via metaprogramming通过元编程填充模板指针类的数组
【发布时间】:2021-04-07 18:08:27
【问题描述】:

基本上我想要一个指向模板类的静态指针数组。一种从索引对应的模板类的映射或查找表。 我会尝试用下面的代码示例更好地解释我的问题。

#include <iostream>

struct TemplateInterface
{
    virtual int get()  = 0;
};

template<int I>
struct TemplatedStruct : public TemplateInterface
{
    int get() override { return I; }
};

// --------------------------------------------------------------------------
// Refactor this section with metaprogramming so to have classes from 1 to N
// --------------------------------------------------------------------------
static TemplatedStruct<1> one;
static TemplatedStruct<2> two;
static TemplatedStruct<3> three;


static TemplateInterface* TIArray[3] = {&one, &two, &three};
// --------------------------------------------------------------------------


int main() {
    for(int i = 0; i < 3; ++i)
    {
        TemplateInterface* ptr = TIArray[i];
        std::cout << ptr->get() << std::endl;
    }
}

【问题讨论】:

标签: c++ templates metaprogramming template-meta-programming


【解决方案1】:

你可能有

template <std::size_t... Is>
std::array<TemplateInterface*, sizeof...(Is)>
makeInterfaceArray(std::index_sequence<Is...>)
{
    static std::tuple<TemplatedStruct<Is>...> data{};
    return {{ &std::get<Is>(data)... }};
}

template <std::size_t N>
std::array<TemplateInterface*, N> makeInterfaceArray()
{
    return makeInterfaceArray(std::make_index_sequence<N>{});
}


int main() {
    for (TemplateInterface* ptr : makeInterfaceArray<3>())
    {
        std::cout << ptr->get() << std::endl;
    }
}

Demo

【讨论】:

  • 谢谢。看起来很干净,但我无法在这里编译你的代码godbolt.org/z/z618fs ...我错过了什么吗?
  • @giuseppe:错字已修复,并添加了演示。
猜你喜欢
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 2012-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
相关资源
最近更新 更多