隐式转换运算符不会在运算符重载时启动
Implicit conversion operator doesn't kick in with operator overloading
请考虑以下示例:
#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
所做的那样。
它只是隐式转换的一个级别,所以应该执行并考虑它,不是吗?
现场演示
您的运算符是模板化的,因此需要推导模板参数。你不能这样做,因为编译器试图将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
^~~
和其他类似消息。
显式
强制转换为 std::string 对我有用:https://godbolt.org/g/WZG78z
std::string s2 = "Line: "s + std::string(loc) + "n"; // was error
相关文章:
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- <T> 通过模板化运算符重载将 std::complex 乘以双倍
- C++20概念:需要运算符重载
- 使用赋值运算符重载从类中返回jobject
- 在运算符重载定义中使用成员函数(const错误)
- 字节到位运算符重载C++
- 为什么在运算符重载时需要参考?
- 类中 c++ 的运算符 + 重载
- 算术复合运算符重载为非成员
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 交换运算符 + 重载会导致无限递归
- 如何理解新的运算符重载?
- 向量保持复数的运算符重载
- 如何创建运算符重载?
- 链接列表运算符重载没有打印出我想要的内容
- C++:需要帮助了解运算符重载错误
- 使用模板化运算符重载 XOR 运算符失败
- 如何确保接受的C++模板类型使运算符重载?
- 运算符重载使用运算符+添加类模板