通过C ++切换在运行时选择模板实例化 [英] Choosing a template instantiation at runtime though switch in C++
问题描述
我有一组由整数类型 Index
和类类型 T
组成的函数,我以下面的方式部分专门化:
I have a set of functions that are templated both by an integer type Index
and a class type T
, that I "partially specialize" in the following manner:
// Integer type
enum Index{One,Two,Three,Four};
// Default implementation
template<int I>
struct Foo{
template<typename T> static void bar(const T& x){ std::cout <<"default" << endl; }
};
// Template specializations
template<>
struct Foo<One>{
template<typename T> static void bar(const T& x){ std::cout << "one" << endl; }
};
这是我用来在程序运行时使用切换语句选择一个特定索引(应该会产生一个有效的查询表)。开关独立于 T
:
This I use to select a particular index at the runtime of the program using a switch-statement (which should result in an efficient look-up table). The switch is independent of T
:
template<typename T>
void barSwitch(int k, const T& x){
switch(k){
case ONE: Foo<ONE>::bar(x); break;
case TWO: Foo<TWO>::bar(x); break;
case THREE: Foo<THREE>::bar(x); break;
}
}
这当然很好,但是该类 Foo
不是我要为其应用切换的唯一类。实际上,我有很多类都由相同的整数类型作为模板。因此,我也想使用功能 Foo对上面的类 barSwitch
进行模板化,以便可以插入其他类或功能。我唯一想到的方法是使用宏:
This works fine, of course, but the class Foo
is not the only class for which I would like to apply the switch. In fact, I have a lot of classes that are all templated by the same integer type. So I would like to "template" the class barSwitch
above with the function "Foo" as well, so that I can plug in a different class or a different function. The only way I can think of to achieve this is to use a macro:
#define createBarSwitch(f,b) \
template<typename T> \
void barSwitch(int k, const T& x){ \
switch(k){ \
case ONE: f<ONE>::b(x); break; \
case TWO: f<TWO>::b(x); break; \
case THREE: f<THREE>::b(x); break; \
}\
}
是否有更好的,更多的C ++
Is there some better, more C++ style way of doing this?
推荐答案
模板模板参数是关键:
enum Index { One, Two, Three, Four };
template <template <Index> class Switcher, typename T>
void barSwitch(int k, const T & x)
{
switch (k)
{
case 1: Switcher<One>::template bar<T>(x); break;
case 2: Switcher<Two>::template bar<T>(x); break;
default: assert(false);
}
}
用法:
template <Index I> struct Foo
{
template <typename T> static void bar(const T & x);
};
barSwitch<Foo>(1, Blue);
(您有责任确保用每个可能的模板代替当然,Switcher
的成员模板为 bar
。如果没有,则会出现编译错误。)
(It is your responsibility to ensure that every possible template that you substitute for Switcher
has a member template bar
, of course. If not, you'll get a compile error.)
这篇关于通过C ++切换在运行时选择模板实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!