2012-10-30 89 views
1

看到下面的代码,debug和show convert在iPhone模拟器和设备(4S)上都成功了,但我不知道它是如何工作的?见http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/,boost :: int64_t没有重载函数。使用std :: stringstream将boost :: int64_t大数转换为字符串。

如果我使用此函数来转换任何任意boost :: int64_t类型,有什么风险?提前致谢。

std::stringstream mySS; 
boost::int64_t large = 4294967296889977; 
mySS<<large; 
std::string str = mySS.str(); 
+0

当然,这种语言并没有与它自己的操作符来提升类型。这就是为什么我们可以超载他们。 – chris

+0

它工作的原因是'boost:int64_t'实际上是一个内建类型的typedef(通常是在cstdint或类似的东西中定义的'std :: int64_t'),所以它最终可能会和'long (或类似的,取决于平台),当然还有'stringstream :: operator <<'的重载。 – jogojapan

+0

@jogojapan,呵呵,我想这很有道理,但我不知道。即使没有提升,仍然可能使运营商超负荷运转。另外,cplusplus列表不完整。在那里没有提及的“long long”和“unsigned long long”有重载。 – chris

回答

2

它的工作原理的原因是boost:int64_t真是一个typedef到内置型(通常std::int64_tcstdint或类似的东西定义的),所以它可能最终被同long long(或类似的,取决于平台)。当然,对于这一点,有一个超载stringstream::operator<<

有关确切定义,请参阅boost/cstdint.hpp(1.51版本)。

假设这通常适用于所有主要平台,这可能是一个相对安全的赌注。但我怀疑任何人都可以为此提供保证。

如果您使用std::stringstream的目的是在整数和字符串之间进行转换,最简单的方法就是使用Boost自己的转换方法:boost::lexical_cast(1.51版本)。这是它是如何完成的:

#include <iostream> 
#include <boost/cstdint.hpp> 
#include <boost/lexical_cast.hpp> 

int main() 
{ 
    boost::int64_t i = 12; 
    std::string s = boost::lexical_cast<std::string>(i); 

    std::cout << s << std::endl; 
    return 0; 
} 
+0

谢谢你,你提供的方法更安全。 – jianhua

相关问题