How can I detect if a type can be streamed to an std::ostream?

前端 未结 6 1549
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 00:41

I\'m trying to write a type trait to detect if a type has overloaded operator<<() suitable to use to an output stream.

I\'m missing something because I\'m alwa

6条回答
  •  無奈伤痛
    2020-12-13 00:56

    "Inspired" by ypw's answer (ypw - if you edit yours accordingly - or create a new one to get rid of the downvotes - I'll delete this and upvote yours):

    template 
    class is_streamable
    {
        template  // must be template to get SFINAE fall-through...
        static auto test(const U* u) -> decltype(std::cout << *u);
    
        static auto test(...)        -> std::false_type;
    
     public:
        enum { value = !std::is_same::value };
    };
    

    Discussion

    The main point of this answer is to highlight how pointless all the worry about rvalue/lvalue references, declvar, forwarding etc. is for this problem. Remember we're just doing a compile time assertion that the streaming notation's supported - there's no run-time for run-time efficiency considerations such as types of references to matter, nor is there a need to use declvar to create a stream as though there was none available. This code keeps it simple and I believe it has full utility - evidence to the contrary most welcome.

提交回复
热议问题