Why doesn't C++ reimplement C standard functions with C++ elements/style?

后端 未结 10 2584
花落未央
花落未央 2020-12-10 05:46

For a specific example, consider atoi(const std::string &). This is very frustrating, since we as programmers would need to use it so much.

10条回答
  •  一整个雨季
    2020-12-10 05:54

    Another more general question is why do not STL reimplementate all the standard C libraries

    Because the old C libraries do the trick. The C++ standard library only re-implements existing functionality if they can do it significantly better than the old version. And for some parts of the C library, the benefit of writing new C++-implementations just isn't big enough to justify the extra standardization work.

    As for atoi and the like, there are new versions of these in the C++ standard library, in the std::stringstream class.

    To convert from a type T to a type U:

    T in;
    U out;
    std::stringstream sstr(in);
    sstr >> out;
    

    As with the rest of the IOStream library, it's not perfect, it's pretty verbose, it's impressively slow and so on, but it works, and usually it is good enough. It can handle integers of all sizes, floating-point values, C and C++ strings and any other object which defines the operator <<.

    EDIT:In addition,I have heard many other libraries avaliable for C++ make a lot of enhancement and extensions to STL.So does there libraries support these functions?

    Boost has a boost::lexical_cast which wraps std::stringstream. With that function, you can write the above as:

    U out = boost::lexical_cast(in);
    

提交回复
热议问题