Choosing a template instance at run time, although in C ++

I have a set of functions that are templated by both an integer type Indexand a class type T, which I "partially specialize" as follows:

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

I use this to select a specific index at run time using the switch statement (which should lead to an efficient lookup 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 , . , , . " " barSwitch "Foo", . , , - :

#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; \
  }\
}

- , ++?

+5
2

- :

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, . , .)

+6
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.

0

All Articles