代码之家  ›  专栏  ›  技术社区  ›  stusmith

使用boost创建一个lambda函数

  •  2
  • stusmith  · 技术社区  · 15 年前

    是否可以使用boost创建一个总是抛出异常的内联lambda?

    (这个问题从 "Using boost to create a lambda function which always returns true" ).

    void Foo( boost::function<bool(int,int,int)> predicate );
    

    如果我想用总是抛出异常的谓词调用它,请定义一个helper函数:

    bool AlwaysThrow( int, int, int ) { throw std::exception(); }
    ...
    Foo( boost::bind( AlwaysThrow ) );
    

    (注1:我不能使用C++ 0x)。

    (注2:我简化了这个例子。我实际的“predicate”函数不返回bool,它返回的类型没有默认的ctor。)

    1 回复  |  直到 8 年前
        1
  •  4
  •   kennytm    15 年前

    a throw_exception function

    For example :

    #include <boost/lambda/lambda.hpp>
    #include <boost/lambda/exceptions.hpp>
    #include <boost/function.hpp>
    
    #include <exception>
    #include <iostream>
    
    struct Bar {
        private:
            Bar() {}
    };
    
    void Foo(boost::function<Bar(int,int,int)> predicate) {
        std::cout << "should show" << std::endl;
        predicate(1,2,3);
        std::cout << "should not show" << std::endl;
    }
    
    int main () {
        Foo( boost::lambda::ret<Bar>(boost::lambda::throw_exception( std::exception() ) ) );
        return 0;
    }