2

我可以创建一个boost::phoenix::lambda按价值捕获的产品。但是,尝试修改由 value 捕获的变量会产生以下错误

error: read-only variable is not assignable
    BOOST_PROTO_BINARY_DEFAULT_EVAL(=, assign, make_mutable, make)

有道理,然后通过引用捕获。通过引用捕获会在 clang 3.2 中产生以下错误:

error: call to 'ref' is ambiguous
    auto a = lambda(_a = ref(dv), _b = ref(i))[ _a[arg1] = _b, _a[arg1] ];
                         ^~~

/usr/include/c++/v1/__functional_base:388:1: note: candidate function [with _Tp =
      std::__1::vector<double, std::__1::allocator<double> >]
ref(_Tp& __t) _NOEXCEPT
^
/usr/local/include/boost/phoenix/core/reference.hpp:68:12: note: candidate function [with T
      = std::__1::vector<double, std::__1::allocator<double> >]
    inline ref(T & t)
           ^

在下面的示例中,我需要通过引用来捕获以获取与 C++11 lambda 等效的代码。通过引用捕获的正确方法是boost::phoenix::lambda什么?

最小的例子:

#include<iostream>
#include<vector>
#include<boost/phoenix/phoenix.hpp>
using namespace boost::phoenix;
using namespace boost::phoenix::placeholders;
using namespace boost::phoenix::local_names;

template<class D = void> struct A {
  A() : i(1), dv(2,2) {}
  int i; std::vector<int> dv;
  void fun() {
    //auto a = [&](int j){ dv[j] = i; return dv[j]; }; // C++11

    // boost::phoenix capture by value works, does not modify dv.
    //auto a = lambda(_a = val(dv), _b = val(i))[ _a[arg1] + _b];

    // boost::phoenix capture by value: modifying the vector does not work.
    auto a = lambda(_a = val(dv), _b = val(i))[ _a[arg1] = _b, _a[arg1] ];

    // boost::phoenix capture by reference: doesn't work.
    auto a = lambda(_a = ref(dv), _b = ref(i))[ _a[arg1] = _b, _a[arg1] ];
    for(size_t t = 0; t != dv.size(); ++t) {
      std::cout << "vt: " << a()(t) << std::endl;
    }   
  }
};

int main() {
  A<void> a;
  a.fun();
  return 0;
}

更新 1:已删除using namespace std;(Xeo 在评论中建议)。

4

0 回答 0