我正在使用代理类型来推迟工作,直到将结果分配给一个变量,它通过在代理类型上使用转换运算符来工作。为 std::string
添加转换运算符重载时,它适用于从代理构建字符串,但无法编译赋值,并显示以下错误消息:
error: ambiguous overload for 'operator='
虽然这个问题与 operator T() not used in assignment 的问题类似,这里的解决方案不适用,因为我也在使用模板化转换运算符。
下面是片段:
#include <iostream>
#include <string>
struct Proxy
{
template < typename T >
operator T ()
{
T res;
std::cerr << "Converting to T: " << typeid( T ).name() << "\n";
return res;
}
operator std::string ()
{
std::string res;
std::cerr << "Converting to string\n";
return res;
}
};
int main()
{
struct Foo {};
Proxy proxy;
bool b = proxy; // Construct, works
b = proxy; // Assignment, works
Foo f = proxy; // Construct, works
f = proxy; // Assignment, works
std::string s = proxy; // Construct, works
s = proxy; // Assignment, this line fails to compile <<<<<
return 0;
};
如何使这个代理与字符串赋值一起工作?
最佳答案
How can this proxy be made to work with the string assignment?
编译器无法判断您想要什么转换。它可以是任何可用于构造 std::string
- char
、char *
、std::string
, ...
所以解决办法就是告诉编译器你想要什么。进行显式运算符(operator)调用:
s = proxy.operator std::string();
关于c++ - std::string 的转换运算符无法处理赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54621668/