Dynamic dispatching of template functions?

前端 未结 5 787
挽巷
挽巷 2020-12-10 14:02

Is it possible to decide in run-time which template function to call? Something like:

template
struct A {
    static void foo() {/*...*/}
};

vo         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-10 14:44

    Depending on what you want to do exactly (i.e. is there a small number of limited instantiations that you want to use?) you can create a lookup table and then use that dynamically. For a fully manual approach, with options 0, 1, 2, and 3, you could do:

    void bar( int i ) {
       static void (*lookup[])(void) = { &A<0>::foo, &A<1>::foo, &A<2>::foo, &A<3>::foo };
       lookup[i]();
    }
    

    Of course, I chose the simplest option for the example. If the number you need are not consecutive or zero based, you might prefer a std::map rather than an array. If the number of different choices you want to use is larger, you might want to add code to automatically intantiate the templates, rather than manually typing all of them... But you would have to consider that each instantiation of the template creates a new function, and you might want to check whether you actually need that.

    EDIT: I have written a post implementing the same initialization using only C++03 features, it seemed too long for an answer.

    Luc Danton wrote an interesting answer here that includes among other things initialization of the lookup table using C++0x constructs. I don't quite like from that solution that it changes the interface to require an extra argument, but that can easily be solved through an intermediate dispatcher.

提交回复
热议问题