Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a smart pointer support invoking a member function via a pointer?

Tags:

c++

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>

class BASE
{
public:
    int fun1(int i){return i * 1;}
};

int main(){
    int (BASE::*pf2)(int);
    boost::shared_ptr<BASE> pB = boost::make_shared<BASE>();
    pf2 = &BASE::fun1;
    std::cout << (pB->*pf2)(3) << std::endl; // compile wrong: error: no match for 'operator->*' in 'pB ->* pf2'|
}

Does this mean the Boost library do not implement '->*' operator to support the use it to invoke member function pointer?

like image 418
Roger Luo Avatar asked Sep 01 '26 21:09

Roger Luo


2 Answers

You should write:

std::cout << ((*pB).*pf2)(3) << std::endl;

As I checked, Boost does not define operator ->* for any of the pointers, although it is possible (see C++ standard, sections 5.5 and 13.5).

Also, the C++11 standard does not define this operator for C++11 smart pointers.

like image 68
Rafał Rawicki Avatar answered Sep 03 '26 09:09

Rafał Rawicki


I would guess that you should do it this way:

std::cout << ((*pB).*pf2)(3) << std::endl;

although it's not tested.

like image 25
Griwes Avatar answered Sep 03 '26 11:09

Griwes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!