如何将任何内容隐式转换为字符串? [英] How to convert anything to string implicitly?

查看:75
本文介绍了如何将任何内容隐式转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是设计一个装饰std :: string的String类,以便提供程序所需的某些功能.我要添加的一项功能是能够将任何内容隐式转换为我的String以便节省键入内容的功能.

My goal is to design a String class that decorates std::string in order to provide some functionality my program needs. One functionality I want to add is the ability to convert anything to my String implicitly in order to save some typing.

为了实现隐式转换,我设计了以下类:

In order to achieve the implicitly conversion I designed the following class:

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类型.

This works fine with any type that has the <<operator defined. The problem came up with any class that doesn't have the stream operator. A compiler error would be fine but what I got is an infinity recursion since C++ tries to use my global << operator to try to convert to my String type.

我的主要目标是编写这样的代码

My primary objective is to code like this

class Foo {
    int _memberWithUnderscoreInName;
}

String s = Foo();

并获得编译器错误,而不是构造函数中的无限循环.

And get a compiler error instead of an infinite loop in the constructor.

有一个简单的解决方案吗?

Is there a simple solution for this?

推荐答案

与其在周围的命名空间中声明输出运算符,不如将其声明为String类的朋友:

Instead of declaring the output operator in the surrounding namespace, only declare it as a friend of the String class:

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 << value的候选者,如果没有其他候选者,则会给出编译错误,而不是运行时死亡螺旋.

Now it can only be found by argument-dependent lookup, and so will only be considered if the second argument really is of type String, not just convertible to it. Therefore, it won't be considered as a candidate for os << value in the constructor, giving a compile error rather than a run-time death spiral if there is no other candidate.

这篇关于如何将任何内容隐式转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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