c++templatestemplate-meta-programmingtemplate-templates

Template function member as template parameter


I want to call different template member functions with the same sequence of input types, in order to reduce boilerplate code, I tried to implement a dispatcher function, for_each_type,


struct A {
    template<typename T>
    void a() {}

    template<typename T>
    void b() {}

    template<template<typename> class Fn>
    void for_each_type() {
        Fn<char>();
        Fn<int>();
        Fn<float>();
        ...
    }
};

int main() {
    A obj;

    // This doesn't compile
    // obj.for_each_type<A::a>();
    // obj.for_each_type<A::b>();
}

Is it possible to implement such a function ?


Solution

  • You can't use template template parameters to identify a function template, but you could provide class templates that in turn return a function pointer to the correct instance of the function, here called a_ptr and b_ptr.

    Example:

    struct A {
        template<typename T>
        void a() {}
    
        template<class T>
        struct a_ptr {
            auto operator()() { return &A::a<T>; }
        };
    
        template<typename T>
        void b() {}
    
        template<class T>
        struct b_ptr {
            auto operator()() { return &A::b<T>; }
        };
    
        template<template<class> class Fn>
        void for_each_type() {
            (this->*Fn<char>{}())();
            (this->*Fn<int>{}())();
            (this->*Fn<float>{}())();
        }
    };
    

    Then, you'd need to provide the class template a_ptr or b_ptr instead:

    int main() {
        A obj;
    
        obj.for_each_type<A::a_ptr>();
        obj.for_each_type<A::b_ptr>();
    }
    

    Demo