我有
template <int i> struct a { static void f (); };
在代码中的不同位置进行专业化。我如何才能在运行时调用正确a<i>::f
的i
已知值?
void f (int i) { a<i>::f (); } // won't compile
我不想i
在一个大的switch
.
编辑:
我想到了类似的东西
#include <iostream>
template <int i> struct a { static void f (); };
struct regf {
typedef void (*F)();
enum { arrsize = 10 };
static F v[arrsize];
template < int i > static int apply (F f) {
static_assert (i < arrsize, "");
v[i] = a<i>::f;
return 0;
}
};
regf::F regf::v[arrsize];
template <int i> struct reg { static int dummy; };
template <int i> int reg<i>::dummy = regf::apply<i> ();
void f (int i) { return regf::v[i] (); }
#define add(i) \
template <> struct a<i> : reg<i> { \
static void f () { std::cout << i << "\n"; } \
};
add(1)
add(3)
add(5)
add(7)
int main () {
f (3);
f (5);
}
但它崩溃了(我错过了强制实例化的东西吗?),我不喜欢那个 dummy 不是static const
(并且使用内存),当然这arrsize
比必要的要大。
实际问题:只有在运行时generate (int i)
调用为给定a<i>::generate ()
生成类实例的函数。设计(类)是给定的,它们继承自基类,并且可以随时在代码中的任何地方添加更多的专业化,但我不想强迫每个人手动更改我的,因为这很容易被忘记。a<i>
i
a<i>
generate (i)