【问题标题】:Problem with boost::bind, boost::function and boost::factoryboost::bind、boost::function 和 boost::factory 的问题
【发布时间】:2011-03-16 20:32:35
【问题描述】:

我正在尝试将 boost::bind 与 boost::factory 一起使用,但没有成功

我有这个类 Zambas 有 4 个参数(2 个字符串和 2 个整数)和

class Zambas {

public:

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

      }
    }
};

在其他方法中我有以下调用

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

失败并出现以下编译器错误:

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

我做错了什么?

【问题讨论】:

    标签: c++ boost-bind boost-function


    【解决方案1】:

    bind 函数返回一个双参数仿函数,因为您将构造函数的第三个和第四个参数绑定到占位符值 _1_2。但是,您将结果存储在零参数 function 对象中。

    我发现a reference from six years ago 解释说当你绑定一个函数时你不能省略参数,即使它们是用默认值声明的

    我认为你有三个选择:

    1. 在调用 bind 时提供实际的 int 值,而不是占位符。
    2. 更改f 的声明以指示它存储一个双参数函数,然后在调用它时始终提供这两个值。
    3. 将最后两个参数绑定到变量。请参阅 Boost.Lambda 文档中的 Delaying constants and variables。然后,您可以将这些变量设置为与构造函数声明的默认值相同。要使用默认值,什么也不做。要指定非默认值,请在调用 f 之前为这些变量赋值。

    最后一个选项可能只会使您的代码更难阅读而没有太多好处,因此请改用前两个选项之一。

    【讨论】:

      猜你喜欢
      • 2012-04-18
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 2011-07-11
      • 2012-05-26
      相关资源
      最近更新 更多