【问题标题】:Why is there "no matching function" for my call to mem_fun_ref?为什么我对 mem_fun_ref 的调用没有“匹配函数”?
【发布时间】:2011-05-26 12:28:28
【问题描述】:

我有一些类从基类继承的代码。

那个基类有一个函数,当运行时,它应该调用要由子类实现的函数。也就是说,一般算法对所有孩子都是一样的,但步骤的实现应该有所不同。

template<class T>
class Foo
{
    public:
        Foo(T y):y(y) { for(int i; i < 10; ++i) x.push_back(i); };
    protected:
        virtual bool IsOk(T, int)=0;
        void Run()
        {
            vector<int>::iterator it, bound;
            for(int i; i < 10; ++i)
            {
                cout << "step " << i << endl;
                bound = partition(x.begin(), x.end(), bind2nd(mem_fun_ref(&Foo<T>::IsOk), i));
                for (it=x.begin(); it!=bound; ++it)
                    cout << "  " << *it;
            };
        };
    private:
        vector<int>x;
        T y;
};

class Bar : public Foo<int>
{
    public:
        Bar():Foo<int>(50){this->Run();};
        bool IsOk(int x , int y) {return x == y;}

};

但是,当我这样做时,我收到以下错误消息: no matching function for call to 'mem_fun_ref(bool (Foo&lt;int&gt;::*)(int, int))'

谁能提供一些关于我在做什么的见解?

【问题讨论】:

  • 'mem_fun_ref(bool (Foo&lt;int&gt;::*)(int, int)) 的定义在哪里,你能告诉我们吗?
  • @Als: mem_fun_ref 是标准库函数。
  • @Space:是的,刚刚检查过!我的错。
  • 您所描述的(主函数调用虚方法,后代重写以自定义细节)被称为 模板方法模式,尽管在​​ C++ 上下文中,名称可能有点令人困惑,因为它实际上并不引用 C++ 模板。

标签: c++ inheritance binding virtual-functions overriding


【解决方案1】:

mem_fun_ref 仅适用于带一个或不带参数的函数。要实现您的想法,您必须使用boost::bind(C++0x 标准库的一部分)。

【讨论】:

    【解决方案2】:

    以下是mem_fun_ref 的原型

    template <class S, class T>
      mem_fun_ref_t<S,T> mem_fun_ref (S (T::*f)());
    
    template <class S, class T, class A>
      mem_fun1_ref_t<S,T,A> mem_fun_ref (S (T::*f)(A));
    
    template <class S, class T>
      const_mem_fun_ref_t<S,T> mem_fun_ref (S (T::*f)() const);
    
    template <class S, class T, class A>
      const_mem_fun1_ref_t<S,T,A> mem_fun_ref (S (T::*f)(A) const);
    

    您的mem_fun_ref(bool (Foo&lt;int&gt;::*)(int, int)) dosnt 与其中任何一个匹配,因此出现错误。

    【讨论】:

      猜你喜欢
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2016-01-31
      相关资源
      最近更新 更多