Search code examples
c++lambdac++20

How can I pass a function that must be treated as a member function of template type


I have created the following simplified working example - where a class Manager takes a template argument and must invoke a member function get_timestamp against the template argument.

class Ex1 {
public:
    int timestamp;
    int get_timestamp() {return timestamp;};
    
};


template<typename T>
class Manager {
    
public:
    void process_data(T& type) {
        
        type.get_timestamp(); // 
    }    
    
};


int main()
{
    Manager<Ex1>();

    return 0;
}

I am looking for a solution where I can replace this type.get_timestamp(); to something like type.FUNC(args); where the FUNC is passed into the class separately. Something similar to passing a lambda or std::function but the difference here is I must instruct the class to treat this "lambda"-like function as a member function of the template argument. Is that possible in C++. I am using c++20


Solution

  • You can pass a member function pointer as a template argument:

    template<typename T, int(T::*FUNC)()>
    class Manager {
    public:
        void process_data(T& type) {
            (type.*FUNC)();
        }
    };
    
    Manager<Ex1, &Ex1::get_timestamp> mgr;
    

    Of course you can also pass it as a runtime argument to process_data(), or to the Manager constructor to store as a member variable.