正确使用Boost :: ref ..?

siv*_*udh 2 c++ boost

我该如何编译?错误是当我开始使用boost :: ref()时.我以为boost :: ref用于传递对C++算法类的引用?

  list<Object> lst;
  lst.push_back(Object(1,2.0f));
  lst.push_back(Object(3,4.3f));

  struct between_1_and_10
  {
    int d;
    void operator() (Object& value) 
    { 
      value.a += 5; value.b -= 3.3f; 
      cout << d << endl;
      d += value.a;
    }
  };

  between_1_and_10 val;
  val.d = 4;
  for_each(lst.begin(), lst.end(), boost::ref(val));   // Problem is here
  printf("rg");
Run Code Online (Sandbox Code Playgroud)

编辑这是人们建议的编译器错误:

1>c:\program files (x86)\microsoft visual studio 9.0\vc\include\algorithm(29) : error C2064: term does not evaluate to a function taking 1 arguments
1>        c:\users\swangrun\desktop\minescout work\feat-000-gettargetimages\minescouttest\maintest.cpp(102) : see reference to function template instantiation '_Fn1 std::for_each<std::list<_Ty>::_Iterator<_Secure_validation>,boost::reference_wrapper<T>>(_InIt,_InIt,_Fn1)' being compiled
1>        with
1>        [
1>            _Fn1=boost::reference_wrapper<main::between_1_and_10>,
1>            _Ty=Object,
1>            _Secure_validation=true,
1>            T=main::between_1_and_10,
1>            _InIt=std::list<Object>::_Iterator<true>
1>        ]
Run Code Online (Sandbox Code Playgroud)

Joh*_*itb 12

boost::reference_wrapper(这是什么boost::ref回报)不会超载operator().你可以使用它boost::bind,它有特殊的处理方法(不使用refbind复制提供的函数对象).

但是for_each返回它调用的东西的函数对象.所以就这样做吧

between_1_and_10 val;
val.d = 4;
val = for_each(lst.begin(), lst.end(), val);
printf("rg");
Run Code Online (Sandbox Code Playgroud)

它将调用复制的东西val,并在最后一次调用后返回函数对象.


只是告诉你你可能会在哪里使用boost::ref,因为你似乎在滥用它.想象一个模板,它按值获取其参数,并调用另一个函数:

void g(int &i) { i++; }

template<typename T>
void run_g(T t) { g(t); }
Run Code Online (Sandbox Code Playgroud)

如果您现在想要使用变量调用它,它将复制它.通常,这是一个合理的决定,例如,如果您想将数据作为启动参数传递给线程,则可以将其从本地函数复制到线程对象中.但有时,您可能希望不复制它,而是实际传递引用.这是有boost::reference_wrapper帮助的.以下实际上实现了我们的期望和输出1:

int main() { 
  int n = 0; 
  run_g(boost::ref(n)); 
  std::cout << n << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

对于绑定参数,副本是一个很好的默认值.它也很容易使数组和函数衰减到指针(通过引用接受将T可能是一个数组/函数类型,并会导致一些讨厌的问题).


Imr*_*ala 7

这就是你真正想要的:

for_each(lst.begin(), lst.end(), boost::bind<void>(boost::ref(val),_1  ) );
Run Code Online (Sandbox Code Playgroud)

编辑:OP的要求的一些解释.回想一下for_each()接受一个函数,但你只是传递了一个对你的struct的引用(是的,结构有它的operator()重载但是你没有传递它).bind()基本上"暴露"你的struct中的函数.

EDIT2:"_ 1"的说明可以在下面的评论中找到.