为什么在 std::string 上重载"operator <<"不起作用?

Why does it not work to overload "operator <<" on std::string?

本文关键字:lt 不起作用 operator 重载 std string 为什么      更新时间:2023-10-16
#include <string>
#include <type_traits>
using namespace std;
template
<
    typename CharT,
    template<typename> class Traits,
    template<typename> class Allocator,
    typename RightT,
    typename StringT = basic_string
    <
    CharT,
    Traits<CharT>,
    Allocator<CharT>
    >
>
enable_if_t
<
    is_constructible<StringT, RightT>::value,
    StringT&
>
operator <<(StringT& lhs, const RightT& rhs)
{
    return lhs.append(rhs);
}
int main()
{
    string s1, s2;
    s1 << s2; // compilation error!
    return 0;
}

我的编译器是VS 2015更新3。编译错误消息为:

错误:二进制表达式的操作数无效('basic_string,allocater>'(和字符串(

为什么它没有按预期工作?

编译器给你的信息比那一行多吗?类似于:

26:1: note: template argument deduction/substitution failed:
35:11: note: couldn't deduce template parameter 'CharT'

如果更换

operator <<(StringT & lhs, const RightT& rhs)

带有

operator <<(basic_string<CharT, Traits<CharT>, Allocator<CharT>>& lhs, const RightT& rhs)

它进行编译。

基本上你是本末倒置。如果您已经知道模板args,则可以使用模板args来形成默认模板arg(StringT = ...(。您不能使用默认值来确定参数。

如果您想同时支持basic_string和其他/自定义字符串,您可能需要编写两个专业化或其他什么。

或者意识到你的模板需求到底是什么——你不需要Constructable,你需要"Appendable",所以SFINAE,忽略它是basic_string还是MyCustomString——这无关紧要;唯一重要的是lhs.append(rhs)是否有效(嗯,也许还可以弄清楚它的返回类型…(