【问题标题】:c++ class function as argument to another class functionc++ 类函数作为另一个类函数的参数
【发布时间】:2016-09-23 21:21:46
【问题描述】:

我试图将一个类的模板化成员函数作为另一个类的模板化成员函数的参数传递。我见过几个使用函数指针的例子,但我试图直接传递这个函数参数。

template <class Item> 
class MinHeap

我有这个功能

tempmlate <class Item>
template <class Process>
void inorder (Process f, const int index)
{
    if (index < size())
    {
        inorder(f, index*2 +1);
        f(data[index]);
        inorder(f, index*2 +2);
    }
}

template<item>
class sequ

我有一个函数叫做

void insert(const Item& x);

我正在尝试在 main 中执行此操作:

MinHeap<int>* tree = new MinHeap<int>();
//insert some stuff
sequ<int>* s = new sequ<int>();
tree->inorder(s->insert);

但最后一行给了我错误:

error: reference to non-static member function must be called
tree->inorder(s->insert);

当我用函数替换 s->insert 时,打印

void print(int x)
{
    printf("%d\n", x);
}

效果很好。

如何使用成员函数作为参数?

【问题讨论】:

    标签: c++ function class templates methods


    【解决方案1】:

    &amp;sequ&lt;int&gt;::insert 给你一个指向sequ&lt;int&gt; 类的成员函数insert 的指针。但是,要调用成员函数,您还需要该类的实例。换句话说,你不能在inorder函数中执行f(data[index]);,因为你需要一个对象实例来调用f成员函数。

    示例代码

    #include <iostream>
    #include <string>
    #include <vector>
    
    template<typename T>
    class Bar
    {
    public:
        void barFn(const std::string& data) { std::cout << "Bar<T>::barFn: " << data << "\n"; }
    };
    
    template<typename T>
    class Foo
    {
    public:
        Foo() : mData{ "Hello World" } {}
    
        template<typename C, typename F>
        void fooFn(C* instance, F memFn, size_t n)
        {
            (instance->*memFn)(mData[n]);
        }
    
    private:
        std::vector<std::string> mData;
    };
    
    int main()
    {
        Bar<int> bar;
        Foo<int> foo;
        foo.fooFn(&bar, &Bar<int>::barFn, 0);
    
        return 0;
    }
    

    示例输出

    Bar<T>::barFn: Hello World
    

    Live Example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-10
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      • 2022-01-11
      相关资源
      最近更新 更多