How to print member function address in C++

前端 未结 4 1573
星月不相逢
星月不相逢 2020-12-01 09:40

It looks like std::cout can\'t print member function\'s address, for example:

#include 

using std::cout;
using std::endl;

clas         


        
4条回答
  •  青春惊慌失措
    2020-12-01 10:21

    Pointers to member functions need memory, too. They also have a size. So how about printing out the memory of the pointer:

    template
    std::string to_string(R (T::*func)(Args...))
    {
        union PtrUnion
        {
            R(T::*f)(Args...);
            std::array buf;
        };
        PtrUnion u;
        u.f = func;
    
        std::ostringstream os;
    
        os << std::hex << std::setfill('0');
        for (auto c : u.buf)
            os << std::setw(2) << (unsigned)c;
    
        return os.str();
    }
    

    You can use it this way:

    class TestClass
    {
        void foo();
    };
    
    ...
    
    std::cout << to_string(&TestClass::foo) << std::endl;
    

提交回复
热议问题