Unable to print the value of nullptr on screen

后端 未结 3 961
北荒
北荒 2020-12-06 18:33

I was reading about nullptr and doing workout on g++ and also on VS2010.

When I did

#include 
using namespace std;

aut         


        
3条回答
  •  误落风尘
    2020-12-06 18:55

    I ran into this problem while I was writing some type-parameterized test code (using templates). I needed to print a value of type T, where nullptr_t was a valid type for T. I came up with a solution where the value to be printed was wrapped inside a printable template function. This function then makes use of template specialization to provide the desired behavior when a nullptr_t is used.

    #include 
    #include 
    
    template  struct Printable
    {
        Printable(const T& val) : val(val) {}
        void print(std::ostream& out) const {out << val;}
        const T& val;
    };
    
    template <> struct Printable
    {
        Printable(nullptr_t) {}
        void print(std::ostream& out) const {out << "null";}
    };
    
    template 
    Printable printable(const T& value) {return Printable(value);}
    
    template 
    std::ostream& operator<<(std::ostream& out, const Printable& p)
    {
        p.print(out);
        return out;
    }
    
    int main() {
        std::cout << printable(42) << " " << printable(nullptr) << "\n";
        return 0;
    }
    

    Ideone link

提交回复
热议问题