to_string is not a member of std, says g++ (mingw)

前端 未结 13 1322
不思量自难忘°
不思量自难忘° 2020-11-22 05:41

I am making a small vocabulary remembering program where words would would be flashed at me randomly for meanings. I want to use standard C++ library as Bjarne Stroustroup t

13条回答
  •  轮回少年
    2020-11-22 06:05

    If we use a template-light-solution (as shown above) like the following:

    namespace std {
        template
        std::string to_string(const T &n) {
            std::ostringstream s;
            s << n;
            return s.str();
        }
    }
    

    Unfortunately, we will have problems in some cases. For example, for static const members:

    hpp

    class A
    {
    public:
    
        static const std::size_t x = 10;
    
        A();
    };
    

    cpp

    A::A()
    {
        std::cout << std::to_string(x);
    }
    

    And linking:

    CMakeFiles/untitled2.dir/a.cpp.o:a.cpp:(.rdata$.refptr._ZN1A1xE[.refptr._ZN1A1xE]+0x0): undefined reference to `A::x'
    collect2: error: ld returned 1 exit status
    

    Here is one way to solve the problem (add to the type size_t):

    namespace std {
        std::string to_string(size_t n) {
            std::ostringstream s;
            s << n;
            return s.str();
        }
    }
    

    HTH.

提交回复
热议问题