mr_*_*org 9 c++ boost boost-format
以下是不可能的:
std::string s = boost::format("%d") % 1; // error
Run Code Online (Sandbox Code Playgroud)
你必须明确地调用str()方法:
std::string s = (boost::format("%d") % 1).str(); // OK
Run Code Online (Sandbox Code Playgroud)
它只是语法糖,但为什么不加入转换呢?
Big*_*oss 11
我认为这个的原因是相同的std::stringstream,在那个上下文中你还应该使用.str()将流转换为字符串并且相同,boost::formatter原因如下:
std::string s1 = "Hello ", s2 = "World";
format("%s.") % s1 + s2;
Run Code Online (Sandbox Code Playgroud)
现在如果可以boost::formatter隐式转换为std::string那么它会生成"Hello .World",因为format("%s.") % s1它将被转换为"Hello".然后它将被隐式转换为std::string并用于operator+添加它s2,但可能大多数程序员都希望拥有"Hello World".这将是一个错误的混乱源.但是在没有隐式转换的情况下,编译器会为此生成错误(因为没有operator+for boost::formatter和std::string),并且您可以将其更正为format("%s.") % (s1 + s2)或str( format("%s.") % s1 ) + s2
如果隐式转换可以抛出异常,那不是一件好事.默认情况下,如果输入的参数format少于需要,则转换为字符串将抛出异常.例如
std::string f()
{
boost::format fmt("%d");
// forgot to feed an argument
std::string s = fmt; // throws boost::io::too_few_args
widget.set_title( fmt ); // throws boost::io::too_few_args
return fmt; // throws boost::io::too_few_args
}
Run Code Online (Sandbox Code Playgroud)
这种隐式转换使得很难发现和分析可能抛出异常的代码部分.但显式.str()调用提供了一些这样的可能异常的暗示,这使得在确保周围代码的异常安全时更加容易,以及(在这种特殊情况下)暗示要仔细检查前面的代码以防止首先发生异常.
| 归档时间: |
|
| 查看次数: |
8638 次 |
| 最近记录: |