2

私は次のものを持っています:

class Foo
{
public:
   std::string const& Value() const { return /*Return some string*/; }
};

typedef std::list<Foo> FooList;
FooList foos; // Assume it has some valid entities inside

std::vector<int> ints;

FooList::const_iterator it, iend = foos.end();
for (it = foos.begin(); it != iend; ++it)
{
   ints.push_back(boost::lexical_cast<int>(it->Value()));
}

std::for_eachandを使用して for ループを実装するにはどうすればよいboost::phoenixですか? 私はいくつかのアプローチを試しましたが、本当に醜いものになりました(ネストされたbind()ステートメントがたくさんありました)。基本的には、Boost phoenix がこの for ループをどのように作成できるかを確認したいだけなので、1 ~ 2 行の特殊なロジックを持つコンテナーを反復処理するボイラープレート コードはあまり作成していません。

時々、C++11 より前のラムダを実行することは、あまりにも読みにくく、メンテナンスが困難であると思われるため、問題を解決する価値がありません。

4

1 に答える 1

1

Phoenix に適した関数オブジェクトを準備するとします。

namespace lexical_casts
{
    template <typename T> struct to_
    {
        template <typename/*V*/> struct result { typedef T type; };
        template <typename V>
        T operator()(V const& v) const { return boost::lexical_cast<T>(v); }
    };

    boost::phoenix::function<to_<int> > to_int;
}

次のようなものを書くことができます:

BOOST_AUTO(value_of, phx::lambda[ phx::bind(&Foo::Value, arg1) ]);

std::vector<int> ints;
boost::transform(
        foolist,
        back_inserter(ints), 
        lexical_casts::to_int(value_of(arg1)));

Coliruでライブを見る

于 2014-03-12T00:38:23.877 に答える