为什么在 std::string 上重载"operator <<"不起作用?
Why does it not work to overload "operator <<" on std::string?
#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)
是否有效(嗯,也许还可以弄清楚它的返回类型…(
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- 我已经完成了<<运算符重载,但它'It’不起作用