【问题标题】:Why Isn't to_string Templatized?为什么 to_string 没有模板化?
【发布时间】:2015-01-23 14:52:02
【问题描述】:

我认为to_string 只是模板化并在后台使用stringstream

不是这样吗?

我希望能够做到这一点:

class foo{};

ostream& operator<<(ostream& os, const foo& /*bar*/){
    os << "foo";
    return os;
}

int main() {
    foo bar;
    string tsTest = to_string(bar);

    return 0;
}

但显然这不起作用,因为 to_string 没有模板化。

【问题讨论】:

  • foo 的命名空间中定义一个to_string 重载,然后通过using 导入该命名空间怎么样?那段代码 sn-p 中的 ostream 需要什么?
  • std::stringstream 不是最有效的转换方式,所以也许这就是它没有模板化的原因,所以每个重载都使用更有效的函数?
  • @peppe 在代码片段中需要operator&lt;&lt; 我认为允许to_string 使用stringstream 插入“foo”。问题出在哪里,为什么to_string 不使用stringstream
  • documentation 可以明显看出std::to_string 是一组沼泽标准重载,而不是函数模板。
  • 对于初学者来说,std::to_string 是根据sprintf 定义的,而不是std::ostringstream。很有可能,其意图是可以通过这种方式实现。

标签: c++ c++11 tostring stringstream stream-operators


【解决方案1】:

不,to_string 不适用于任何类型。原始标准类型只有重载。不幸的是,它不能取代boost::lexical_cast

【讨论】:

  • 在即将到来的 TS 中,boost::lexical_cast 是否可供未洗过的大众使用?
  • @JonathanMee: It was proposed for TR2,至少在某个时候。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-23
  • 1970-01-01
  • 2011-06-21
  • 2013-07-10
  • 2017-01-22
  • 1970-01-01
相关资源
最近更新 更多