通过在C ++中切换,在运行时选择模板实例化

时间:2012-02-16 22:23:39

标签: c++

我有一组由整数类型Index和类类型T模板化的函数,我可以部分地专注于"以下列方式:

// 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; }
};

这用于在程序的运行时使用switch语句选择特定的索引(这应该会产生一个高效的查找表)。该开关独立于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并不是我想要应用这个开关的唯一类。事实上,我有很多类都是由相同的整数类型模板化的。所以我想&#34;模板&#34;上面的类barSwitch,功能为&#34; Foo&#34;同样,我可以插入不同的类或不同的功能。我能想到的唯一方法是使用宏:

#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 ++风格的方式呢?

2 个答案:

答案 0 :(得分:6)

模板模板参数是关键:

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。如果没有,您将收到编译错误。)

答案 1 :(得分:0)

template<template<int> class F>
struct BarFunc {};


template<>
struct BarFunc<Foo> {
    template<Index I, typename T>
    static void call(const T& x) {
        Foo<I>::bar(x);
    }
};


template<template<int> class F, typename T>
void barSwitch(int k, const T& x) {
    switch(k){
    case One: BarFunc<F>::call<One>(x); break;
    case Two: BarFunc<F>::call<Two>(x); break;
    case Three: BarFunc<F>::call<Three>(x); break;
    }
}

您可以通过提供BarFunc专精来参数化要调用的函数。