I’ve read the various authorities on this, include Dewhurst and yet haven’t managed to get anywhere with this seemingly simple question.
What I want to do is to call a C++ function object, (basically, anything you can call, a pure function or a class with ()), and return its value, if that is not void, or “true” otherwise.
using std:
struct Foo {
void operator()() { cout << "Foo/"l; }
};
struct Bar {
bool operator()() { cout << "Bar/"; return true; }
};
Foo foo;
Bar bar;
bool baz() { cout << "baz/"; return true; }
void bang() { cout << "bang/"; }
const char* print(bool b) { cout << b ? "true/" : "false/"; }
template <typename Functor> bool magicCallFunction(Functor f) {
return true; // Lots of template magic occurs here
// that results in the functor being called.
}
int main(int argc, char** argv) {
print(magicCallFunction(foo));
print(magicCallFunction(bar));
print(magicCallFunction(baz));
print(magicCallFunction(bang));
printf("\n");
}
// Results: Foo/true/Bar/true/baz/true/bang/true
UPDATE
Thanks for the thoughts and ideas!
Based on this, I actually decided to bring up all my templating one level – so instead I have:
bool eval(bool (*f)()) { return (*f)(); }
bool eval(void (*f)()) { (*f)(); return true; }
template <typename Type>
bool eval(Type* obj, bool (Type::*method)()) { return (obj->*method)(); }
template <typename Type>
bool eval(Type* obj, void (Type::*method)()) { (obj->*method)(); return true; }
and generic classes to carry the various objects and methods around. Thanks to Mr.Ree for the code that pushed me in that direction!
Wouldn’t it be easier to implement an overloaded no-op version of print(void)?
Ahh well. Function templates and overloading will easily handle this at runtime.
It gets somewhat stickier if you had wanted to handle this at compile time, for use with #if macros or static-compile-time-asserts.
But since you only want the former, may I suggest something like this as a starting point:
(Tested under (GCC) 3.4.4 & 4.0.1. — I know, I need to upgrade!)
Okay, I begin to see more of the problem.
While we can do something along the lines of this:
You do still have that nasty need to feed &CLASS::operator() in as an argument.
Ultimately, while we can determine whether the object’s operator() method returns a void, we cannot normally overload based on return types.
We can get around that overloading limitation via template specialization. But then we get into this uglyness wherein we still need to specify types… Especially the return type! Either manually, or by passing in a suitable argument from which we can extract the necessary types.
BTW: #define macros won’t help either. Tools like ?: require the same type for both the ? and : part.
So this is the best I can do…
Of course…
If you don’t need the return type…
If you are just passing the result to another function…
You can do something like this: