我知道
Java或C#似乎太多了.但是,使我自己的类作为函数std :: to_string的输入有效/可能/很明智吗?
例:
例:
class my_class{ public: std::string give_me_a_string_of_you() const{ return "I am " + std::to_string(i); } int i; }; void main(){ my_class my_object; std::cout<< std::to_string(my_object); }
如果没有这样的事情(我认为那样),最好的办法是什么?
解决方法
首先,一些ADL的帮助:
namespace notstd { namespace adl_helper { using std::to_string; template<class T> std::string as_string( T&& t ) { return to_string( std::forward<T>(t) ); } } template<class T> std::string to_string( T&& t ) { return adl_helper::as_string(std::forward<T>(t)); } }
notstd :: to_string(blah)将对范围内的std :: to_string执行to_string(blah)的ADL查找.
然后我们修改你的课程:
class my_class{ public: friend std::string to_string(my_class const& self) const{ return "I am " + notstd::to_string(self.i); } int i; };
现在nostd :: to_string(my_object)找到正确的to_string,和notstd :: to_string(7)一样.
原文地址:https://www.jb51.cc/c/111805.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。