2010-08-25 66 views
2

是否有可能使用总是抛出异常的boost创建内联lambda?使用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:我已经简化这个例子中我实际的 “断言” 功能不返回一个bool。它会返回一个没有default-ctor的类型。)

回答

4

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; 
} 
相关问题