-2

I am trying to create a constructor that will take in a lambda function with unknown type and unknown parameters. I have managed to get it to work with passing a function that has no parameters, but when I attempt to add parameters to the function I cannot understand how to match the argument list.

cpp file

#include "TestBind.h"

using namespace std;
int main()
{
    int i = 10;

    function<int(int, int)> Multiply = [&i](int a, int b)
    {
        i = 11;
        return i * a * b;
    };

    g<int,int,int> n (Multiply); //problem line
    n.runFunc();
    cout << i << endl;

    cin.clear();
    cin.ignore();
    cin.get();
}

h file

#include <functional>
#include <iostream>

using namespace std;

template <typename ReturnType, typename... Args>
class g
{
public:
    g(Args... args, function<ReturnType(Args...)> func) { f = func; };
    void runFunc() {
        cout << f() << endl;
    };
    ~g() {};

private:
    function<ReturnType(Args...)> f;
};

I am pretty sure that this has been answered here, but I don't understand how to implement the solution.

I should expand on what I am actually trying to do. I am trying to make a class that will later be used to make buttons in opengl. These buttons can have a function with unknown return types and unknown arguments (types and amount). I am trying to make a test currently where I just make an object that I can pass a function with those requirements and then run the function (as if I had clicked the button) Once I have this I already have the opengl side handled I was just trying to make a proof of concept. I am using an std::function/lambda function since I thought the use of the capture would be beneficial.

Greg Ford
  • 1
  • 1

1 Answers1

0

Not clear what you are trying to do. Perhaps you are looking for something like this:

class g
{
public:
    template <typename F, typename... Args>
    g(F&& func, Args&&... args) {
        f = [=]() { std::cout << func(args...) << std::endl; };
    }
    void runFunc() {
        f();
    };

private:
    std::function<void()> f;
};

Demo

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85