gpt4 book ai didi

c++ - 隐式转换运算符不参与运算符重载

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:42:38 25 4
gpt4 key购买 nike

考虑以下示例:

#include <string>
#include <sstream>

struct Location {
unsigned line;

template<typename CharT, typename Traits>
operator std::basic_string<CharT, Traits>() const {
std::basic_ostringstream<CharT, Traits> ss;
ss << line;
return ss.str();
}
};

int main()
{
using namespace std::string_literals;

Location loc{42};

std::string s1 = "Line: "s.append(loc) + "\n"s; // fine
//std::string s2 = "Line: "s + loc + "\n"s; // error
}

注释行导致编译错误:no match for 'operator+'。为什么?我最初的想法是,它会先使用operator std::string 进行转换,然后执行对operator+ 的调用,与.append< 的处理方式相同

这只是一层隐式转换,所以应该执行并且应该考虑到,不是吗?

Live Demo

最佳答案

您的运算符是模板化的,因此需要推导模板参数。你不能这样做,因为编译器试图匹配 basic_string<_CharT, _Traits, _Alloc>给你的Location , 它失败了。

所以问题在于重载,而不是转换,因为代码实际上从未达到这一点。

改变这个:

std::string s2 = "Line: "s + loc + "\n"s;

为此:

std::string s2 = "Line: "s + std::string(loc) + "\n"s;

你应该没问题,因为如果你仔细查看编译器错误,它会提到:

template argument deduction/substitution failed:
prog.cc:22:32: note: 'Location' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>'
std::string s2 = "Line: "s + loc + "\n"s; // error
^~~

和其他类似的消息。

关于c++ - 隐式转换运算符不参与运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46843003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com