开发者

Using boost to create a lambda function which always throws

Is it possible to create an inline lambda using boost which always throws an exception?

(this question follows on from "Using boost to create a lambda function which always returns true").

Suppose I have a function which takes some form of predicate:

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

If I want to call it with a predicate that always throws an exception, define a helper function:

bool AlwaysThrow( int, int, int ) { throw std::exception(); }
...
Foo( boost::bind( A开发者_如何学编程lwaysThrow ) );

But is there anyway to call this function (possibly using boost::lambda) without having to define a separate function?

(Note 1: I can't use C++0x.)

(Note 2: I've simplified this example. My actual "predicate" function doesn't return a bool, it returns a type which doesn't have a default-ctor.)


There is a throw_exception function in Boost.Lambda.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜