几年后,C+17与@v.oddou进行了讨论,终于提供了一种方法来完成最初基于宏的类型无关解决方案(保留在下面)。无经历了宏观的丑恶。// variadic templatetemplate std::string sstr( Args &&... args ){
std::ostringstream sstr;
// fold expression
( sstr <
return sstr.str();}
用法:int i = 42;std::string s = sstr( "i is: ", i );puts( sstr( i ).c_str() );Foo x( 42 );
throw std::runtime_error( sstr( "Foo is '", x, "', i is ", i ) );
原文:
因为“转换.为字符串”是一个反复出现的问题,所以我总是定义SSTR()宏在我的C+源的中央标题中:#include #define SSTR( x ) static_cast( \ ( std::ostringstream() <
使用非常容易:int i = 42;std::string s = SSTR( "i is: " <
:runtime_error( SSTR( "Foo is '" <
以上内容与C+98兼容(如果不能使用C+11)std::to_string),并且不需要任何第三方包含(如果不能使用Boost)。lexical_cast<>这两种解决方案都有更好的性能。