How to print function pointers with cout?

前端 未结 7 2444
挽巷
挽巷 2020-11-22 07:09

I want to print out a function pointer using cout, and found it did not work. But it worked after I converting the function pointer to (void *), so does printf with %p, such

7条回答
  •  旧时难觅i
    2020-11-22 07:20

    There actually is an overload of the << operator that looks something like:

    ostream & operator <<( ostream &, const void * );
    

    which does what you expect - outputs in hex. There can be no such standard library overload for function pointers, because there are infinite number of types of them. So the pointer gets converted to another type, which in this case seems to be a bool - I can't offhand remember the rules for this.

    Edit: The C++ Standard specifies:

    4.12 Boolean conversions

    1 An rvalue of arithmetic, enumeration, pointer, or pointer to member type can be converted to an rvalue of type bool.

    This is the only conversion specified for function pointers.

提交回复
热议问题