制作用户定义的类 std::to_string-able [英] Making a user-defined class std::to_string-able

查看:28
本文介绍了制作用户定义的类 std::to_string-able的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Java 或 C# 似乎太多了.但是,将我自己的类作为函数 std::to_string 的输入是否可能/好/明智?示例:

class my_class{民众:std::string give_me_a_string_of_you() const{返回我是"+ std::to_string(i);}国际我;};无效主(){my_class my_object;std::cout<

如果没有这样的事情(而且我认为没有),那么最好的方法是什么?

解决方案

首先,一些 ADL 帮助:

命名空间 notstd {命名空间 adl_helper {模板std::string as_string( T&& t ) {使用 std::to_string;return to_string( std::forward(t) );}}模板std::string to_string( T&& t ) {返回 adl_helper::as_string(std::forward(t));}}

notstd::to_string(blah) 将使用 std::to_string 在范围内对 to_string(blah) 进行 ADL 查找.

然后我们修改你的类:

class my_class{民众:朋友 std::string to_string(my_class const& self) {返回我是"+ notstd::to_string(self.i);}国际我;};

现在 notstd::to_string(my_object) 找到合适的 to_stringnotstd::to_string(7) 也是如此.>

通过更多的工作,我们甚至可以支持自动检测和使用类型的 .tostring() 方法.

实例

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?

解决方案

First, some ADL helping:

namespace notstd {
  namespace adl_helper {
    template<class T>
    std::string as_string( T&& t ) {
      using std::to_string;
      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) 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;
};

and now notstd::to_string(my_object) finds the proper to_string, as does notstd::to_string(7).

With a touch more work, we can even support .tostring() methods on types to be auto-detected and used.

Live example

这篇关于制作用户定义的类 std::to_string-able的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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