为什么不能在用户定义的转换中将cout与std :: string一起使用? [英] Why cannot use cout with user-defined conversion to std::string?

查看:77
本文介绍了为什么不能在用户定义的转换中将cout与std :: string一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我定义一个 Date ,并指定一个用户定义的转换.

Here I define a Date, and specify a user-defined conversion.

class Date {
private:
    int day;
    int month;
    string dateStr;
public:
    Date(int _day, int _month) : day(_day), month(_month) {}

    operator const string() {
        ostringstream formattedDate;
        formattedDate << month << "/" << day;
        dateStr = formattedDate.str();
        return dateStr;
    }
};

当转换为 string 时,效果很好.

It works well when converting to string.

Date d(1, 1);
string s = d;

但是为什么不能直接将它与 cout 一起使用?

But why cannot use it with cout directly?

cout << d << endl; // The compiler complains that there is no suitable type marching << operator

但是,如果我使用 char * 而不是 string 进行用户定义的转换,则可以直接将其与 cout 一起使用.为什么?

However, if I use char* instead of string for user-defined conversion, I can use it with cout directly. Why?

operator const char*() { 
    ostringstream formattedDate;
    formattedDate << month << " / " << day;
    dateStr = formattedDate.str();
    return dateStr.c_str();
}

ps.我知道直接重载<< 可以很好地用于输出.但是我的问题是:为什么不能在用户定义的转换为 std :: string 的情况下使用<< ?

ps. I know that overloading << directly will work well for output. But my question is: why cannot use << with user-defined conversion to std::string?

推荐答案

请注意, std :: string 是模板 std :: basic_string std :: string的 operator<< 的签名 确实是:

Note that std::string is an instantiation from template std::basic_string, the signature of operator<< for std::string is indeed:

template <class CharT, class Traits, class Allocator>
std::basic_ostream<CharT, Traits>& 
    operator<<(std::basic_ostream<CharT, Traits>& os, 
               const std::basic_string<CharT, Traits, Allocator>& str);

然后是 cout<<d; ,必须推导 std :: basic_string 的模板参数;但是类型推导不考虑隐式转换;

then for cout << d;, the template parameter of std::basic_string has to be deduced; but type deduction does not consider implicit conversions;

类型推导不考虑隐式转换(上面列出的类型调整除外):这是超载解析的工作,稍后会发生.

Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.

这意味着扣除将失败;那么没有候选函数是可行的.

That means the deduction would fail; then no candidate function is viable.

但是 operator<< for const char * 没有这种问题;隐式转换生效,然后正常工作.

But operator<< for const char* hasn't such kind of problem; implicit conversion takes effect and then works fine.

要解决此问题,可以使用显式转换来避免模板参数的推导;或直接在 Date 类型上重载 operator<< .

To solve the issue, you can use explicit conversion to avoid template argument deduction; or overload operator<< on the type Date directly.

这篇关于为什么不能在用户定义的转换中将cout与std :: string一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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