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.
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.
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.
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 C++ struct have member functions? Yes, they can.
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
."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With