-1

0成功と!= 0エラーを示すために戻るCスタイルの関数がいくつかあります。それらを、値を返す代わりに関数
に「ラップ」したいと思います。voidthrow

私はこのヘルパーを書きました:

void checkStatus(int status) {
  if (status != 0)
    // throw an error object
}

次に、確定関数をラップするためint tilt(float degrees)に、次を使用しますboost::bind

function<void(float)> ntilt = bind(checkStatus, bind(tilt, _1));
ntilt(30); // this will call checkStatus(tilt(30))

そしてそれは素晴らしい働きをします。しかし、専用のラッパー関数が欲しいので、次のことができます。

function<void(float)> ntilt = wrap(tilt);
ntilt(30); // this will call checkStatus(tilt(30))

を返すすべての関数/シグニチャで機能するはずintです。
Boostを使用してそれを行うための最良の方法は何でしょうか?

4

1 に答える 1

3

ラップされた関数が取る可能性のあるさまざまな量のパラメーターを処理するために、いくつかのオーバーロードを作成できます。

// handles 1 parameter functions
template<typename Ret, typename T0>
function<void(T0)> wrap(Ret (*fun)(T0)) {
    return bind(checkStatus, bind(fun, _1));
}

// handles 2 parameters functions    
template<typename Ret, typename T0, typename T1>
function<void(T0, T1)> wrap(Ret (*fun)(T0, T1)) {
    return bind(checkStatus, bind(fun, _1, _2));
}

// ... add more

これがC++11の実装です。が必要ない場合は、いくつかのことを回避できますがstd::function、それでも機能します。

#include <functional>
#include <stdexcept>

template<typename Ret, typename... Args>
struct wrapper {
    typedef Ret (*function_type)(Args...);

    void operator()(Args&&... args) {
        if(fun(std::forward<Args>(args)...) != 0)
            throw std::runtime_error("Error");
    }

    function_type fun;
};

template<typename Ret, typename... Ts>
std::function<void(Ts...)> wrap(Ret (*fun)(Ts...)) {
    return std::function<void(Ts...)>(wrapper<Ret, Ts...>{fun});
}

これがライブデモです。

于 2013-03-25T15:55:03.830 に答える