could some please explain this syntax for C++ functor
I was interested is the colon : after add_x(int x)Code:struct add_x {
add_x(int x) : x(x) {} // please expain this
int operator()(int y) { return x + y; } // and this
Printable View
could some please explain this syntax for C++ functor
I was interested is the colon : after add_x(int x)Code:struct add_x {
add_x(int x) : x(x) {} // please expain this
int operator()(int y) { return x + y; } // and this
That's an initializer list. You may find one in any constructor.
The second one is the operator for casting to int, both explicitly and implicitly with static_cast<int>(object)
I know for experienced developers it it might be mundane stuff , please elaborate I am try to port an application to CUDA thrust C++ API , the real easy way is to pass a functor , similar to
std:: transform with vector array CUDA in parallel will perform all calculations in paralles , the thrust::transform works similar to std version except it is a whole lot faster ,
For some reason I have difficulty warping my head around C++ functor construct ( may be a mental block )
No, the second one overloads the function call operator such that this function can be invoked using syntax that makes it appear like an add_x object is a function that takes an int argument and returns an int, i.e., a function object (functor).Quote:
Originally Posted by ninja9578
Correct me if I'm wrong, but I think the second one is an overload of the function call operator that returns the sum of the argument and the data member as an int. So, you could do something like this:
The value of y would be 60.Code:add_x obj(50);
const int y = obj(10);
You could do this instead,
For constructors it's considered best practice to use an initialization list. It can also be a little faster.Code:struct add_x {
add_x(int a) {x = a;} // variable assignment of constructor parameter not using an intialization list
int fun(int y) {return x + y}; // definition of your own functor function not following the () convention
You can define any functor function you like but since most functor enabled code follows the overloaded () operator convention it's better to stick with it.
thank you all