【发布时间】: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;
}
}
【问题讨论】:
-
您确定要它们为 const 吗?你正在用那个 const_cast 和 UB 调情
-
@Jarod42 和 [at]AndyG 谢谢,我的错。我已将问题更新为更简单明了。
标签: c++ templates metaprogramming template-meta-programming