【问题标题】:Using boost to create a lambda function which always throws使用 boost 创建一个总是抛出的 lambda 函数
【发布时间】:2011-04-03 15:02:04
【问题描述】:

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

(这个问题来自"Using boost to create a lambda function which always returns true")。

假设我有一个采用某种谓词形式的函数:

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

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

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

但是无论如何都可以调用这个函数(可能使用 boost::lambda)而不必定义一个单独的函数?

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

(注 2:我已经简化了这个例子。我实际的“谓词”函数不返回布尔值,它返回一个没有默认向量的类型。)

【问题讨论】:

    标签: c++ boost lambda


    【解决方案1】:

    Boost.Lambda 中有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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-28
      • 2018-01-13
      • 1970-01-01
      • 2023-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      相关资源
      最近更新 更多