Thread: c++ equivalent of c# delegate/lambda

  1. #1
    Registered User
    Join Date
    May 2010
    Posts
    3

    c++ equivalent of c# delegate/lambda

    Hi,

    In c# i'm used to the following:
    Code:
    public class Foo{
    
        public void Fun(CustomExceptionHandler customHandler){
            try{
                // ...
            }
            catch(DerivedExceptionType1 ex){ /* Custom handle the exception... */ }
            catch(DerivedExceptionType2 ex){ /* Custom handle the exception... */ }
            catch(DerivedExceptionType3 ex){ /* Custom handle the exception... */ }
        }
    
        public delegate void CustomExceptionHandler(Exception ex);
    }
    
    public void Fun(){
    
        Foo foo = new Foo();
        foo.Fun( ex => ClientExceptionHandler(ex) );
    }
    
    public void ClientExceptionHandler(Exception ex){
    
        if(ex.GetType() == typeof(DerivedExceptionType1){
           // ...
        }
        else if(ex.GetType() == typeof(DerivedExceptionType2){
            // ...
        }
        else{ // ... }
    Can anyone give an example of something similar in C++.
    Using boost is fine, and it certainly doesn't have to be about handling exceptions.
    Just something that shows how function pointers relate to lambdas?

  2. #2
    The larch
    Join Date
    May 2006
    Posts
    3,573
    For the particular example, lambda doesn't seem to be necessary. Just use boost::bind, boost::function, or just a plain function pointer, e.g:

    Code:
    template <class CustomExceptionHandler>
    void Fun(CustomExceptionHandler handler);
    
    foo.Fun(&ClientExceptionHandler);
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Equivalent of Dos 'copy' in C ?
    By YetBo in forum C Programming
    Replies: 17
    Last Post: 11-04-2009, 10:10 PM
  2. Pointer equivalent to array notation
    By bekkilyn in forum C Programming
    Replies: 4
    Last Post: 12-06-2006, 08:22 PM
  3. C++ Equivalent JPEG Functions?
    By stickman in forum C++ Programming
    Replies: 9
    Last Post: 05-06-2006, 10:50 AM
  4. Replies: 10
    Last Post: 08-17-2005, 11:17 PM
  5. Header File Question(s)
    By AQWst in forum C++ Programming
    Replies: 10
    Last Post: 12-23-2004, 11:31 PM