Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining operator() function inside a struct

Tags:

c++

boost

While going through one of the tutorials in the Boost library on function wrappers here, I came across the following code:

  1     boost::function<float (int x, int y)> f;
  2
  3     struct int_div {
  4         float operator() (int x, int y) const { return ((float)x)/y; }
  5     };
  6
  7
  8     int main()
  9     {
 10         f = int_div();
 11         cout << f(5, 3) << endl;
 12         return 0;
 13     }

I am trying to wrap my head around about defining a function (operator()) inside a struct, and then assigning the struct (using () ) to the function wrapper f. Can someone please help me understand what is happening, as far as concepts, in lines 3-5 and 10.

like image 590
Ahmed A Avatar asked Mar 18 '14 19:03

Ahmed A


People also ask

Can you define a function inside a struct?

No, you can't. Structs can only contain variables inside, storing function pointers inside the struct can give you the desired result. Save this answer.

Can you have functions in struct C++?

Structs can have functions just like classes. The only difference is that they are public by default: struct A { void f() {} }; Additionally, structs can also have constructors and destructors.

Can a struct hold functions?

Structs hold only data and classes hold data and functions. Classes in C++ are used in the exact same as they are in Java. You have the objects of a class. You can think of a class as a type.

Can a function be a member of struct?

Can C++ struct have member functions? Yes, they can.


2 Answers

In C++, you can provide operators for your types. As function call (()) is just another operator in the language, it's possible to define it for your types. So the definition inside int_div says "objects of type int_div can have the function call operator applied to them (with operands int and int); such a call will return a float."

boost::function is a wrapper around anything callable. Since an object of type int_div can be used with the function call operator, it's callable and can thus be stored in a boost::function. The types match as well - the operator in int_div is indeed of type float(int, int).

The parentheses on line 10 are not a call of this operator, however; they are a constructor call. So the line says "create an object of type int_div using the default constructor of that type, and assign that object into f."

like image 142
Angew is no longer proud of SO Avatar answered Oct 24 '22 09:10

Angew is no longer proud of SO


If you were using C++11, you could write line #10 as:

f = int_div{};

which probably help with your confusion. This line creates a temporary object of type int_div, and then assigns it to f.

It's not a function call, even though it looks like one.

like image 6
Marshall Clow Avatar answered Oct 24 '22 10:10

Marshall Clow