制作用户定义的类std :: to_string(able) [英] Making a user-defined class std::to_string(able)
问题描述
我知道Java或C#似乎太多了。但是,是否可以/可以/明智地使我自己的类作为函数 std :: to_string
的输入有效?
示例:
I know it seems too much Java or C#. However, is it possible/good/wise to make my own class valid as an input for the function std::to_string
?
Example:
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);
}
如果没有这样的东西(我认为),那是什么最好的方法?
If there is no such thing (and I think that), what is the best way to do it?
推荐答案
首先,一些ADL帮助:
First, some ADL helping:
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(等等)
将使用 std :: to_string
to_string(blah)进行ADL查找
notstd::to_string(blah)
will do an ADL-lookup of to_string(blah)
with std::to_string
in scope.
然后我们修改您的课程:
We then modify your class:
class my_class{
public:
friend std::string to_string(my_class const& self) {
return "I am " + notstd::to_string(self.i);
}
int i;
};
现在是 notstd :: to_string(my_object)
找到正确的 to_string
,以及 notstd :: to_string(7)
一样。
and now notstd::to_string(my_object)
finds the proper to_string
, as does notstd::to_string(7)
.
需要更多的工作,我们甚至可以为要自动检测和使用的类型支持 .tostring()
方法。
With a touch more work, we can even support .tostring()
methods on types to be auto-detected and used.
这篇关于制作用户定义的类std :: to_string(able)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!