Tho*_*mas 5 c++ templates template-specialization
我有
template <int i> struct a { static void f (); };
Run Code Online (Sandbox Code Playgroud)
在代码中的不同位置完成专业化.如何仅在运行时调用正确a<i>::f
的知识i
?
void f (int i) { a<i>::f (); } // won't compile
Run Code Online (Sandbox Code Playgroud)
我不想列出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);
}
Run Code Online (Sandbox Code Playgroud)
但它崩溃了(我是否错过了一些强制实例化的东西?),我不喜欢那个虚拟不是static const
(并且使用内存),当然这arrsize
比必要的要大.
实际问题:有一个函数只在运行时generate (int i)
调用为给定a<i>::generate ()
的类生成一个实例.给出了设计(类),它们继承自基类,并且可以在代码中的任何地方随时添加更多的a特化,但我不想强迫每个人手动更改,因为这可能很容易被遗忘.a<i>
i
a<i>
generate (i)
我不确定这是你可以获得的最佳解决方案,因为可能有更好的设计,无论如何你可以使用一些元编程来触发函数的实例化和注册表:
// in a single cpp file
namespace {
template <unsigned int N>
int register_a() { // return artificially added
register_a<N-1>(); // Initialize array from 0 to N-1
regf::v[N] = &a<N>::f; // and then N
return N;
}
template <>
int register_a<0>() {
regf::v[0] = &a<0>::f; // recursion stop condition
return 0;
}
const int ignored = register_a<regf::arrsize>(); // call it
}
Run Code Online (Sandbox Code Playgroud)
该代码将实例化函数并注册指向静态成员函数的指针.伪返回类型需要能够在静态上下文中强制执行该函数(通过使用该函数初始化静态值).
这很容易发生静态初始化惨败.虽然没问题regf::v
,但是regf::v
在静态初始化期间依赖于包含适当指针的任何代码都将失败.您可以使用常规技术改进这一点......
根据您实际发布的点点滴滴,我的猜测是您尝试使用抽象工厂,并从每个具体工厂自动注册.有更好的方法来解决问题,但我认为这个答案解决了你的问题(我不确定这是否能解决你的问题).