开发者

Handling a C++ libsigc++ signal with a lambda function

I'm working on some C++ code that uses libsigc++ for signaling (eventing.)

I'm quite new to C++, and I tend to think in C#. The equivalent code to what I want in C# would be something like:

var names = new List<string>();
thing.Happened += (string name) => names.Add(name);
thing.DoStuff();

The libsigc++ tutorials do a good job of showing how to bind a function or member to a signal, but I don't want to define a new class-le开发者_高级运维vel method for such a simple method that should really be privately encapsulated within its client, at least to my thinking.

The libsigc++ API seems to support lambda expressions, but I haven't found any examples showing how to use them. Can someone help me out? Remember that I'm a C++ newbie!


Lambdas are just function objects. So anywhere you can use an arbitrary(i.e. templated) functor, you can use a lambda.

I don't have the library installed, so I can't test this, but looking at this example, I believe this modification should work:

int main()
{
    AlienDetector mydetector;
    auto warn_people = []() {
            cout << "There are aliens in the carpark!" << endl;
    };

    mydetector.signal_detected.connect( sigc::slot<void>(warn_people) );

    mydetector.run();

    return 0;
}

P.S.

I wasn't entirely confident in this answer since I couldn't test it. I found that constructor for the slot class in the documentation, and because I've never encountered a constructor template in a class template, I wasn't sure that the types would all be able to resolve. So anyway, I wrote a test using only the standard library that does something like what that constructor does, and it works. Here it is


C++ 0x supports lambdas and would probably allow you do do something similar to what you do in C#. See What C++ compilers are supporting lambda already? for C++0x ready compilers.


This site on MSDN has a very nicely laid out and comprehensive look at the lambda feature as well as the use of the auto keyword in C++0x. It has some really helpful examples, as well as the connection between lambdas and function-objects from earlier versions of C++. Note that you may have to use the -std=c++0x or 1std=gnu++0x flags if you're using g++ version 4.4 or greater in order to get these features to compile correctly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜