![](/img/trans.png)
[英]QString to std::string to const char* conversion does not work in assignment
[英]Conversion operator for std::string fails to work with assignment
我正在使用代理类型来推迟工作,直到将结果分配给变量为止,它通过对代理类型使用转换运算符来工作。 为std::string
添加转换运算符重载时,它可用于从代理构造字符串,但无法编译以进行赋值,并显示以下错误消息:
错误:“ operator =”的模棱两可的重载
尽管此问题类似于分配中未使用的运算符T()处的问题,但解决方案在此处不适用,因为我也使用模板转换运算符。
以下是代码段:
#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;
};
如何使该代理与字符串分配一起使用?
如何使该代理与字符串分配一起使用?
编译器无法告知您要进行什么转换。 它可以是任何可以用来构造std::string
- char
, char *
, std::string
,...的东西。
因此解决方案是告诉编译器您想要什么。 进行明确的操作员调用:
s = proxy.operator std::string();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.