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

标签 c++ templates c++11 operator-overloading overloading

#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 Update 3,编译报错信息是:

error : invalid operands to binary expression ('string' (aka 'basic_string, allocator >') and 'string')

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

最佳答案

编译器是否为您提供了比那一行更多的信息?像这样的东西:

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)

它编译。<​​/p>

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

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

或者意识到你的模板需求到底是什么——你不需要 Constructible,你需要“Appendable”,所以 SFINAE 就在那上面,忽略它是 basic_string 还是 MyCustomString——没关系;唯一重要的是 lhs.append(rhs) 是否有效(而且,呃,也许还要弄清楚它的返回类型...)

关于c++ - 为什么在 std::string 上重载 "operator <<"不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38548253/

相关文章:

c++ - 检测到堆损坏 | C++

c++ - 推导(非类型)模板参数类型的编译器方差

c++ - 仅用于基本 POD 的模板特化

c++ - 将静态成员的范围限制为 n 个特定类

c++ - 接收文件错误

c++ - CMake 看不到 SDL2_PATH 环境变量 (Windows)

C++ 编程 : Error when assigning the iterator to vector

c++ - std::atomic bool 或 Normal global bool 在单线程中好用吗?

C++ 命名修饰 : QBE_NXZ QAE_NXZ

c++ - 无法访问模板化重载运算符中的私有(private)成员