Created
January 27, 2013 14:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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