2

テンプレートファンクターラッパーから任意の型 (void または非 void) を返す方法は? 事前条件と事後条件にラッパーを使用するため、戻り値をラッパーから返す前にローカル変数に格納する必要があります。しかし、返された型が void の場合、変数は void 型を持つことができないため、コンパイラはエラーを返します。ここで何ができるでしょうか?

template <typename Functor, typename... Args>
auto Decorate(Functor f, Args&&... args)
-> decltype(f(std::forward<Args>(args)...)) {
    // preconditions
    const auto result = f(std::forward<Args>(args)...);
    // postconditions
    return result;
}
4

2 に答える 2

5

適切なクラスのコンストラクタ/デストラクタで事前および事後条件を実行し、値を直接返します! 事後条件で戻り値に触れる必要がない限り、問題にはなりません!

struct condition
{
    condition() { /* do pre-condition checks */ }
    ~condition() { /* do post-condition checks */ }
    condition(condition&) = delete;
    void operator= (condition&) = delete;
};
template <typename Functor, typename... Args>
auto Decorate(Functor f, Args&&... args)
    -> decltype(f(std::forward<Args>(args)...)) {
    condition checker;
    return f(std::forward<Args>(args)...);
}
于 2013-08-29T17:35:40.150 に答える