How to print function pointers with cout?

前端 未结 7 2521
挽巷
挽巷 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条回答
  •  误落风尘
    2020-11-22 07:22

    In C++11 one could modify this behavior by defining a variadic template overload of operator<< (whether that is recommendable or not is another topic):

    #include
    namespace function_display{
    template
    std::ostream& operator <<(std::ostream& os, Ret(*p)(Args...) ){ // star * is optional
        return os << "funptr " << (void*)p;
    }
    }
    
    // example code:
    void fun_void_void(){};
    void fun_void_double(double d){};
    double fun_double_double(double d){return d;}
    
    int main(){
        using namespace function_display;
        // ampersands & are optional
        std::cout << "1. " << &fun_void_void << std::endl; // prints "1. funptr 0x40cb58"
        std::cout << "2. " << &fun_void_double << std::endl; // prints "2. funptr 0x40cb5e"
        std::cout << "3. " << &fun_double_double << std::endl; // prints "3. funptr 0x40cb69"
    }
    

提交回复
热议问题