How to convert anything to string implicitly?

后端 未结 2 1341
失恋的感觉
失恋的感觉 2021-01-06 06:25

My goal is to design a String class that decorates std::string in order to provide some functionality my program needs. One functionality I want to add is the ability to con

2条回答
  •  时光取名叫无心
    2021-01-06 06:53

    This or similar should fix it:

    namespace HasFormattedOutput {
    
        namespace Detail
        {
            struct Failure{};
        }
    
        template
        Detail::Failure operator << (OutputStream&, const T&);
    
        template
        struct Result : std::integral_constant<
            bool,
            ! std::is_same<
                decltype((*(OutputStream*)0) << std::declval()),
                Detail::Failure
            >::value
        > {};
    } // namespace HasFormattedOutput
    
    template 
    struct has_formatted_output
    :   HasFormattedOutput::Result
    {};
    
    class X  {
        public:
        X() {}
    
        template 
        X(const T& t) {
            static_assert(
                 has_formatted_output::value, 
                 "Not supported type.");
            std::ostringstream s;
            s << t;
            str = s.str();
        }
    
        private:
        std::string str;
    };
    std::ostream& operator << (std::ostream& stream, const X&) { return stream; }
    
    struct Y  {
        Y() {}
    };
    
    int main() {
        Y y;
        X x(y);
        return 0;
    }
    

提交回复
热议问题