1

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?

Community
  • 1
  • 1
Omid N
  • 947
  • 2
  • 11
  • 24
  • 5
    Sure, why not? The obvious approach should work, are you facing any particular problem when you try it? –  Nov 06 '16 at 15:51
  • `operator()` is just a funky function-name receiving however many arguments you write down. – Deduplicator Nov 06 '16 at 15:51

1 Answers1

2

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).

  • wow thanks!!! I found out that I made a mistake and wrote my function header like "operator(,)(int x,int y)" – Omid N Nov 06 '16 at 16:06