c – 如何隐式地将任何东西转换为字符串?
发布时间:2020-12-16 09:47:14 所属栏目:百科 来源:网络整理
导读:我的目标是设计一个String类来装饰std :: string,以便提供我的程序所需的一些功能.我想要添加的一个功能是隐式地将任何东西转换为我的String,以节省一些输入. 为了实现隐式转换,我设计了以下类: std::ostream operator(std::ostream o,const String s);clas
我的目标是设计一个String类来装饰std :: string,以便提供我的程序所需的一些功能.我想要添加的一个功能是隐式地将任何东西转换为我的String,以节省一些输入.
为了实现隐式转换,我设计了以下类: std::ostream& operator<<(std::ostream& o,const String& s); class String { public: template<typename t_value> String::String(t_value value) { std::ostringstream oss; oss << value; _str = oss.str(); } private: std::string _str; } 这适用于任何具有<<运算符定义的类型.任何没有流操作符的类都会出现问题.编译器错误会很好,但我得到的是无穷递归,因为C试图使用我的全局<<运算符尝试转换为我的String类型. 我的主要目标是像这样编码 class Foo { int _memberWithUnderscoreInName; } String s = Foo(); 并在构造函数中获得编译器错误而不是无限循环. 有一个简单的解决方案吗? 解决方法
不是在周围的命名空间中声明输出运算符,而是仅将其声明为String类的朋友:
class String { public: // This must be implemented inline here friend std::ostream& operator<<(std::ostream& o,const String& s) { return o << _str; // for example } template<typename t_value> String(t_value value) { std::ostringstream oss; oss << value; _str = oss.str(); } private: std::string _str; }; 现在它只能通过依赖于参数的查找来找到,因此只有在第二个参数确实是String类型时才会被考虑,而不仅仅是可以转换为它.因此,它不会被视为os<<构造函数中的值,如果没有其他候选者,则给出编译错误而不是运行时死亡螺旋. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |