【问题标题】:error: ambiguous overload for ‘operator[]’ when using boost-bind to boost-function错误:使用 boost-bind 到 boost-function 时,'operator[]' 的重载不明确
【发布时间】:2012-07-18 17:11:41
【问题描述】:

我正在尝试根据输入字符串的值将过滤器仿函数映射到我的类的成员方法之一。

#include <iostream>
#include <map>
#include <boost/function.hpp>
#include <boost/cstdint.hpp>
#include <boost/assign.hpp>
#include <boost/bind.hpp>

typedef boost::function < bool(std::map<std::string, std::string>, std::string) > MyFilterFunctor;

class MyClass
{
public:
    bool FilterFunction1(std::map<std::string, std::string> myMap, std::string filterValue)
    {
        //do something
        return true;
    }
};

int main() {

    MyFilterFunctor myFilter = boost::bind(&MyClass::FilterFunction1, _1, _2, _3);
    return 0;
}

我的错误:

/usr/include/boost/bind/bind.hpp:375:
error: ambiguous overload for ‘operator[]’ in ‘a[boost::_bi::storage3<A1, A2, boost::arg<I> >::a3_ [with A1 = boost::arg<1>, A2 = boost::arg<2>, int I = 3]]’

编辑: 根据对我的问题的建议答案的建议,我稍微简化了我的示例。 有人建议我需要将 MyClass() 作为参数传递给 boost::bind,这确实解决了发布的代码段中的编译错误。但是,鉴于我的代码结构,我不可能这样做。我想知道为什么我所做的与 boost::bind 文档中的这个示例不同:

struct X
{
    int f(int);
}

int main()
{ 
    boost::bind(&X::f, 1);     // error, X::f takes two arguments
    boost::bind(&X::f, _1, 1); // OK
}

_1 参数是否应该处理隐含的“this”,建议我使用 MyClass() 显式提供它?

【问题讨论】:

  • 是的,filterKey 是一个 std::string。我将编辑一个变量声明以使其更清晰。
  • 一个自包含的可编译的最小示例,人们可以复制粘贴并尝试自己玩,在这里可能会有所帮助。
  • @PlasmaHH 谢谢你的建议,我刚做了。

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


【解决方案1】:

这与boost::assign::map_list_ofstd::map无关,同样的错误可以通过这个简单的重现:

MyFilterFunctor mff;
auto bb = boost::bind(&MyClass::FilterFunction1, _1, _2, _3);
mff = bb;

bb 需要 3 个参数:MyClassmap&lt;string,string&gt;stringmff 需要 2 个参数,一个 map&lt;string,string&gt; 和一个 string。这两者显然是不相容的。

改用boost::bind(&amp;MyClass::FilterFunction1, MyClass(), _1, _2))

【讨论】:

  • 感谢您富有洞察力的回复。我的理解是,第一个参数 _1 将采用“this”参数,该参数隐含在对成员函数的调用中。这将避免我必须将显式调用作为参数之一传递给该类的构造函数,因为我的代码的结构方式不允许我这样做
  • @user1535568:如果MyFilterFunctor 类型也接受了MyClass&amp; 参数?
  • @user1535568,如果你不想调用构造函数来创建这样的对象,this对象应该从哪里来?也许您的方法应该是静态的,因此它不需要this 指针?如果您需要传递的对象中没有任何内容,那么static 应该可以正常工作。
  • @MvG 谢谢,这实际上只是把我想做的事情放在眼里,你是对的。成员函数可以是静态的,我不需要指向 this 的指针。
猜你喜欢
  • 1970-01-01
  • 2016-03-16
  • 2012-04-18
  • 2012-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多