if 文の遅延処理?


ある値(関数の戻り値等)が true だった場合に呼ばれる関数をあらかじめ設定してしまうとかそんな感じ。
とりあえず、何も考えずに実装してみる。

#include <iostream>

#include <boost/function.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/at_c.hpp>

namespace fusion = boost::fusion;

typedef boost::function<bool()> if_type;
typedef boost::function<void()> then_type;
typedef boost::function<void()> else_type;

typedef fusion::vector<if_type, then_type, else_type> if_then_else_type;

void
call(if_then_else_type& func){
    if( fusion::at_c<0>(func)() ){
        fusion::at_c<1>(func)();
    }
    else{
        fusion::at_c<2>(func)();
    }
}

int
main(){
    bool b = true;

    if_then_else_type
    if_([&](){ return b; },
        [](){
            std::cout << "true" << std::endl;
        },
        [](){
            std::cout << "false" << std::endl;
        }
    );

    b = true;
    call(if_);
    
    b = false;
    call(if_);
    
    return 0;
}


[出力]

true
false


うーん、もうちょっとスマートにしたいですねぇ……。