Omid Najafi Omid Najafi - 1 month ago 24
C++ Question

Functors with two variables or more

I'm kinda new to C++11 and I read this post about functors and It was very helpful, I just thought that is it possible to make a functor that receives more than a single variable?
for example we have the class below:

class my_functor{
public:
my_functor(int a,int b):a(a),b(b){}

int operator()(int y)
{
return a*y;
}

private:
int a,b;

};


Now I wonder is there any way that we could make a member function like

operator()(int y)


but with 2 or more (or unknown numbers!) of variables being received?

Answer

Yes. You can pass as many arguments as you want to operator(). See for example:

#include <iostream>
class my_functor{
public:
    my_functor(int a,int b):a(a),b(b){}

    int operator()(int y)
    {
        return a*y;
    }

    int operator()(int x, int y)
    {
        return a*x + b*y;
    }

private:
    int a,b;
};

int main()
{
    my_functor f{2,3};
    std::cout << f(4) << std::endl; // Output 2*4 = 8
    std::cout << f(5,6) << std::endl; // Output 2*5 + 6*3 = 28
    return 0;
}

To handle an unknown number of arguments, you need to look at the various solutions for handling variable number of arguments (basically, #include <varargs.h>, or template parameter packs).