Boost.Phoenix で、Boost.Lexical_cast を使う

もうちょっと複雑なコードになるかと思いましたが、function を使えばそんなに難しくありませんでした。
関数の戻り値型をどうするかちょっと悩みましたが、元々関数オブジェクトなので、boost::result_of で取得出来るんですね。

[ソース]

#include <boost/phoenix.hpp>
#include <boost/lexical_cast.hpp>

template<typename T>
struct lexical_cast_impl{
    typedef T result_type;
    template<typename U>
    result_type
    operator ()(U const& u) const{
        return boost::lexical_cast<T>(u);
    }
};

template<typename T, typename U>
typename boost::result_of<
    boost::phoenix::function<lexical_cast_impl<T> >(U const&)
>::type
lexical_cast(U const& u){
    return boost::phoenix::function<lexical_cast_impl<T> >()(u);
}


#include <string>
#include <iostream>

int
main(){
    namespace phx = boost::phoenix;
    using phx::arg_names::arg1;
    using phx::local_names::_a;
    
    std::string str = ::lexical_cast<std::string>(arg1)(10);
    std::cout << str << std::endl;
    int n = ::lexical_cast<int>(phx::ref(str))();
    std::cout << n << std::endl;

    return 0;
}

[出力]

10
10

こういうのはもっと欲しいですねー。

[boost]

  • ver 1.47.0