Problem with boost::bind, boost::function and boost::factory

别来无恙 提交于 2019-12-10 21:25:56

问题


I'm trying without success to use a boost::bind with a boost::factory

I have this class Zambas with 4 arguments (2 strings and 2 ints) and

class Zambas {

public:

Zambas(const std::string&, const std::string&,int z1=0,int z2=0) {    
      if (z1==z2){

      }
    }
};

inside other method i have the following call

boost::function<Zambas*()> f(boost::bind(boost::factory<Zambas*>(), std::string(""), std::string(""),_1,_2));

that fails with the following compiler error:

bind.hpp:382: error: no match for ‘operator[]’ in ‘a[boost::_bi::storage3<A1, A2, boost::arg<I> >::a3_ [with A1 = boost::_bi::value<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, A2 = boost::_bi::value<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, int I = 1]]’

What I'm doing wrong ?


回答1:


The bind function returns a two-argument functor because you bound the third and fourth parameters of your constructor to the placeholder values _1 and _2. However, you're storing the result in a zero-argument function object.

I found a reference from six years ago explaining that you can't omit parameters when you bind a function, even if they're declared with default values.

I think you have three options:

  1. Provide actual int values in your call to bind instead of placeholders.
  2. Change the declaration of f to indicate that it stores a two-argument function, and then always provide both values when you call it.
  3. Bind the last two parameters to variables. See Delaying constants and variables in the Boost.Lambda documentation. Then, you can set those variables to the same default values as the constructor declares. To use the default values, do nothing more. To specify non-default values, assign values to those variables before calling f.

The last option will probably just make your code harder to read without much benefit, so prefer one of the first two options instead.



来源:https://stackoverflow.com/questions/5331385/problem-with-boostbind-boostfunction-and-boostfactory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!