Is there any way to bring some functional programming to C++ , I want deliver some LAMBDA function or operators as parameter to another function.
for example :
void test(DWORD foo)
{
try { __asm { call foo; } } // very weird way, don't think that could work
catch (...) { () }
}
or :
void test2(DWORD foo)
{
someconnection.Open();
__asm { call foo; } // very weird way, don't think that could work
someconnect开发者_如何转开发ion.Close();
}
and usage alike :
int main ()
{
...
dosomething();
...
void operator()(int n) // lambda expression, not sure if that correct way creating them
{
dosomething();
dosomethingelse();
}
test ( *operator(5) ) // here is what I want
test2 ( *operator(10) ) // here is what I want
...
dosomethingelse();
...
}
I'm using Visual Studio 2010 and not sure if I can use C++0x there but I can use boost if that can do what I want to do.
So is there some ways to make it ?
You can, by making the parameter of e.g. test
a std::tr1::function
:
void test(std::tr1::function<void(DWORD)> func) {
func(0);
}
You can call this with a function, a member function or even a lambda:
test([](DWORD param) { return; });
Look into function objects(functors): http://en.wikipedia.org/wiki/Function_object
and lambda in boost: http://www.boost.org/doc/libs/1_46_0/doc/html/lambda.html
There's tons of stuff in boost for that.
However, I'd generally advise against getting too deep into it. The problem is that the implmenetation of things like lambdas in boost gets insanely complicated. I've seen compilations with VS take several minutes for a single source file, and if you do something wrong you get ludicrously long unreadable error messages.
Well, actually the messages are readable in a way, but only if you are very familiar with the implementation of all the boost objects involved. IMHO a client of a facility should not have to know that much about the internals of how a facility is coded to use it.
精彩评论