#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/