【问题标题】:Passing Non-Static Member Function as argument传递非静态成员函数作为参数
【发布时间】:2014-05-30 13:18:54
【问题描述】:

SalesMap.h 摘录-

typedef BST<Sales> BinarySearchTree;//type defined for Sales_Map construction
typedef map<Date, BinarySearchTree> sales_map;//type defined for map construction
sales_map Sales_Map;

SalesMap.cpp 摘录-

Highest 和 SetHigh 都是公开的

void SalesMap::Highest(){
    void (SalesMap::*SetHighPTR)(Sales);//create non-static function pointer
    SetHighPTR = &SalesMap::SetHigh; //assign address of function void SetHigh(Sales sales)
    //it is an iterator to a specific element in Sales_Map
    it->second.InSearch(&SetHighPTR); // pass SetHigh into BST object function InSearch
}

void SalesMap::SetHigh(Sales sales)//test input sales object against global highprice variable
{
    double price = sales.GetPrice();
    if(price < high)
        high = price;
}

BST.h

Public:
     void InSearch(void (*f)(T) );//calls recursive InSearch function
Private:
      void InSearch(node*& leaf, void (*f)(T) );

template <class T>//public InSearch
void BST<T>::InSearch( void (*f)(T) )
{
    InSearch(root, (*f));
}

template <class T>//Private InSearch
void BST<T>::InSearch(node*& leaf, void (*f)(T))
{
    if(leaf != NULL)
    {
        InSearch(leaf->left);
        (*f)(key);
        InSearch(leaf->right);
    }
}

我正在尝试在 BST.h 中创建回调函数。 我不断收到以下错误:

error C2664: 'void BST<T>::InSearch(void (__cdecl *)(T))' : cannot convert parameter 1 from 'void (__thiscall SalesMap::* )(Sales)' to 'void (__cdecl *)(T)'

我不确定该问题所需的正确语法,并且无法弄清楚我应该做什么以及在哪里做。 任何帮助将不胜感激

【问题讨论】:

  • 我建议您重新编辑您的问题并发布一个可重现的小问题示例。
  • 函数指针不同于方法指针
  • boost.bind 解决了这个问题
  • std::bind 也很感兴趣。

标签: c++ callback function-pointers binary-search-tree non-static


【解决方案1】:

问题基本上是您试图将 成员函数指针 转换为 函数指针,这在 C++ 中是不可能的,因为成员函数指针总是需要一个调用它的对象。 (this 需要指向某个地方)

类的静态方法不需要任何对象,因此也是函数指针。

如果你想使用成员函数指针,你的InSearch 方法应该有以下参数:

template <class T>//public InSearch
void BST<T>::InSearch( void (SalesMap::*f)(T) )

那么你需要一个SalesMap 类型的对象或任何派生类来调用这个方法:

//Using an object pointer
(mySalesObjectPtr->*f)(key);
//No pointer
(mySalesObject.*f)(key);

当然,您可以为函数指针创建一个重载,就像您已经完成的那样,它适用于全局函数和静态方法。

this article 的开头很好地概述了这两种类型的函数指针。

【讨论】:

    【解决方案2】:

    这是一个基本示例,当您想从成员类外部传递成员函数的函数指针时。

    class A
    {
    private:
        void(A::*m_myFuncPointer)(); ///declaring a private member function pointer
    
    public:
        void init( void(A::*someFunc)() ){
            m_myFuncPointer = someFunc;    ///stores the function pointer
            (this->*m_myFuncPointer)();    ///calls the function using member function
        }  
        void execute(){
            std::cout<<"hello"<<std::endl;
        }
     };
    
    int main()
    {
        A a;
        a.init(&A::execute);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-18
      • 2019-03-14
      • 2011-05-31
      • 1970-01-01
      • 2020-12-31
      • 2011-01-07
      • 2013-06-29
      • 1970-01-01
      相关资源
      最近更新 更多