标题就已经说明了一切。他们为什么选择不使用一个
标签?
namespace std
{
std::string to_string(const std::string&)
}
重载?
我有一个程序可以通过行索引或行名称查询一些数据;非常适合模板。但是,如果正在访问的行不存在,我尝试构建错误消息时就会出现问题:
template <typename T>
int read(T nameOrIndex)
{
if (!present(nameOrIndex))
{
// This does not compile if T is std::string.
throw std::invalid_argument("Missing row: " + std::to_string(nameOrIndex));
}
}
我可以在std
命名空间中添加自己的重载,但这并不理想。
T
是其他类型之一,你的代码将无法编译。那么其他类型怎么办呢?是否应该有一个返回任意类型字符串的to_string
实现?而不是向std
添加to_string
重载(这是非法的),我会在与read
相同的命名空间中创建自己的to_string
重载。从那里委托给std::to_string
,并从接受std::string const&
的重载中直接返回参数。 - Praetorianstd::to_string
将内置的数字类型转换为字符串。不需要将字符串“转换”为字符串,因为它们已经是字符串。 - Pete Beckerto_string
基本上是C格式化工具的安全接口,它会将缓冲区和其他内容隐藏起来。对于字符串,确实有一个C格式化说明符%s
。因此,显然有一些东西已经丢失了 :) - Chris Beckint x; int y = static_cast<int>(x);
。 - Sebastian Mach