Skip to content

Instantly share code, notes, and snippets.

@ugovaretto
Created January 27, 2013 14:23
Show Gist options
  • Save ugovaretto/4648555 to your computer and use it in GitHub Desktop.
Save ugovaretto/4648555 to your computer and use it in GitHub Desktop.
Directly invoke a function object as a regular function without having to explicitly construct it
//Author: Ugo Varetto
//
//function objects do not allow a call to the object's operator()(...)
//without an explicit creation:
// struct neg {
// int operator()(int i) const { return -i; }
// };
// neg n;
// std::cout << n(4) << std::endl
// or, if the () operator is const
// std::cout << neg()(4) << std::endl;
// prints -4
// the following code allows to call the neg function
// object as 'neg(4)'
// The trick is to replace(or add to) the () operator with:
// - a constructor taking the same arguments as the () operator
// and storing their references internally
// - a conversion operator returning the same type as the () operator
// where the actual operations are performed
#include <iostream>
struct neg {
neg() : n_(0) {} // useful if default-constructible required
neg(const int& n) : n_(&n) {}
operator int() const { return -(*n_);}
const int* n_;
};
int main(int, char**) {
std::cout << neg(4) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment