jeudi 7 novembre 2019

Automatically deduce lambda arguments from member function signature

Usually, I use lambda functions to set callbacks to member functions for 3rd party libraries. For example:

setCallback([this](auto&& ...x) { handleCallback(std::forward<decltype(x)>(x)...); });

Now I have a library with an overloaded function to set the callback, making this line ambiguous:

#include <functional>
#include <iostream>

class Library
{
public:
    typedef std::function<void (int)> IntFunction;
    typedef std::function<void (int, int)> IntIntFunction;

    void setCallback(IntFunction f) { f_int_ = f; }
    void setCallback(IntIntFunction f) { f_int_int_ = f; }

    void callCallback(int a, int b) {
        if (f_int_) f_int_(a);
        if (f_int_int_) f_int_int_(a, b);
    }

private:
    IntFunction f_int_;
    IntIntFunction f_int_int_;
};

class MyClass
{
public:
    MyClass() {
        //lib.setCallback([this](auto&& ...x) { handleCallback(std::forward<decltype(x)>(x)...); });
        lib.setCallback([this](int a, int b) { handleCallback(a, b); });
    }

    void handleCallback(int a, int b) {
        std::cout << "handleCallback: " << a << ", " << b << std::endl;
    }

    Library lib;
};

int main()
{
    MyClass myclass;
    myclass.lib.callCallback(2, 3);
    return 0;
}

Is there a way to automatically deduce the right arguments from the handleCallback function to avoid having a duplicate of the function arguments in the lambda?

Aucun commentaire:

Enregistrer un commentaire