【发布时间】:2011-04-11 13:10:07
【问题描述】:
我有
template <int i> struct a { static void f (); };
在代码的不同位置进行了专门化。如何为仅在运行时知道的i 调用正确的a<i>::f?
void f (int i) { a<i>::f (); } // won't compile
我不想在一个大的switch 中列出i 的所有可能值。
编辑:
我想到了类似的东西
#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 () 为仅在运行时给出的i 生成类a<i> 的实例。给出了设计(a<i> 类),它们继承自基类,并且可以随时在代码中的任何位置添加更多的 a 特化,但我不想强迫每个人手动更改我的 generate (i) 为很容易忘记。
【问题讨论】:
-
再次使用预期的解决方案编写代码,但不是实际问题。询问您要解决的问题。 (不是您预期的解决方案中失败的原因)。你真的需要模板吗?为什么?专长?为什么?需要继承吗?为什么?
-
我无法更改
struct a的设计(它是更大系统的简化部分),但我需要一个低内存f而无需手动更改switch添加的每个专业化。
标签: c++ templates template-specialization