[英]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.