Search code examples
c++eventssignalslibsigc++

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-level 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!


Solution

  • 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