为什么没有std :: stou?

Dav*_*one 92 c++ string std c++11

C++ 11添加了一些新的字符串转换函数:

http://en.cppreference.com/w/cpp/string/basic_string/stoul

它包括stoi(string to int),stol(string to long),stoll(string to long long),stoul(string to unsigned long),stoull(string to unsigned long long).值得注意的是它是一个stou(字符串到无符号)函数.有什么理由不需要它,但所有其他的都是吗?

相关:C++ 11中没有"sto {short,unsigned short}"函数?

Ker*_* SB 28

最轻松的答案是C库没有相应的" strtou",而C++ 11字符串函数都只是围绕C库函数的薄弱包装:std::sto*函数镜像strto*std::to_string函数使用sprintf.


编辑:作为KennyTM指出,无论是stoistol使用strtol作为底层的转换功能,但它仍然是神秘的,为什么而存在stoul使用strtoul,也没有相应的stou.

  • 你知道为什么C++委员会决定采用这种C-ish方法吗?像`boost :: lexical_cast <>()`这样的东西似乎是一种更加C++的做事方式. (14认同)
  • C++标准是否"必须通过调用......来实现"并不重要,因为C++标准仍然具有全局的as-if规则:如果标准说`std :: sto*`必须实现为包装器对于C库函数,一个有效的程序无法判断它们是不是以不同方式秘密实现,实现是有效的. (12认同)
  • @LightnessRacesinOrbit:对于`sto*`,C++ 11 21.5/1:效果:前两个函数调用strtol(str.c_str(),ptr,base),最后三个函数调用strtoul(str.c_str() ,ptr,base),strtoll(str.c_str(),ptr,base)和strtoull(str.c_str(),ptr,base). (4认同)
  • 这些实现细节是否真的是标准定义的? (2认同)
  • 完全偏离主题,我认为不使用像Boost/lexical_cast这样的iostream的实际原因就是纯粹的性能; 我相信iostream会以相当大的差距输掉strtoul等. (2认同)
  • 好吧,我相信`boost :: lexical_cast`专门用于各种类型的最佳性能,因此几乎总是比其他方法具有更好的性能:http://www.boost.org/doc/libs/release/doc/html/ boost_lexical_cast/performance.html (2认同)

Mik*_*our 21

我不知道为什么stoi存在但不是stou,但是stoul假设之间的唯一区别stou是检查结果是否在以下范围内unsigned:

unsigned stou(std::string const & str, size_t * idx = 0, int base = 10) {
    unsigned long result = std::stoul(str, idx, base);
    if (result > std::numeric_limits<unsigned>::max()) {
        throw std::out_of_range("stou");
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

(同样,stoi也类似于stol,只是使用不同的范围检查;但由于它已经存在,因此无需担心具体如何实现它.)