为什么没有to_string(const string&)? [英] Why is there no to_string(const string&)?

查看:128
本文介绍了为什么没有to_string(const string&)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有模板代码,需要将某些模板类型转换为字符串。为此,我为自己的类型重载了to_string。但是类型也可以是字符串。然后编译失败,因为类型字符串本身没有to_string的重载(只是返回其参数)。

I have template code which needs to convert some template type to string. For this I overload to_string for my own types. But the type can also be a string already. Then compilation fails, because there is no overload of to_string for type string itself (just returning its argument).

edit:
示例代码:

edit: example code:

template<class T>
class TemplatedClass
{
public:

string toString() const
{
    // this should work for both simple types like int, double, ...
    // and for my own classes which have a to_string overload
    // and also for string, which is the reason for my question
    return string("TemplatedClass: ").append(to_string(t_));
}

private:
    T t_;
};


推荐答案

您可以编写带有适当重载的模板化函数如下:

You can just write your own templated function with proper overloads as follows:

#include <iostream>
#include <string>
using namespace std;

template<typename T>
std::string toString(const T& t) {
    return std::to_string(t);
}

std::string toString(const char* t) {
    return t;
}

std::string toString(const std::string& t) {
    return t;
}


int main() {
    cout << toString(10) << endl;
    cout << toString(1.5) << endl;
    cout << toString("char*") << endl;
    cout << toString(std::string("string")) << endl;
    return 0;
}

这篇关于为什么没有to_string(const string&amp;)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆