我有以下内容:

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_eachboost::phoenix实现for循环?我尝试了几种方法,但是它真的很难看(我有很多嵌套的bind()语句)。我基本上只是想看看干净和可读的boost phoenix如何使它成为for循环,所以我没有写太多的样板代码来迭代具有1-2行特殊逻辑的容器。

有时,在C++ 11之前执行lambdas似乎太难以理解和难以维护,因此不值得为此烦恼。

最佳答案

假设您准备了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)));

看到它 Live On Coliru

关于c++ - 相当于boost::phoenix的是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22339031/

10-16 04:52