给出以下程序:
#include <iostream>
#include <string>
using namespace std;
struct GenericType{
operator string(){
return "Hello World";
}
operator int(){
return 111;
}
operator double(){
return 123.4;
}
};
int main(){
int i = GenericType();
string s = GenericType();
double d = GenericType();
cout << i << s << d << endl;
i = GenericType();
s = GenericType(); //This is the troublesome line
d = GenericType();
cout << i << s << d << endl;
}
它可以在Visual Studio 11上编译,但不能在clang或gcc上。 它的问题在于它想要从GenericType
隐式转换为int
到char
,但也可能返回一个string
,因此存在歧义(operator =(char)
和operator =(string)
都匹配GenericType
)。
然而复制构造函数正常。
我的问题是:如何在不修改main内容的情况下解决这种歧义?我需要做什么来修改GenericType
以处理这种情况?
explicit operator int()
зӯүгҖӮиҝҷеҸҜд»ҘеғҸдҪҝз”ЁgetType()
еҮҪж•°дёҖж ·жңүж•Ҳең°йҳІжӯўй”ҷиҜҜпјҢеӣ дёәз”ЁжҲ·еҝ…йЎ»жҳҫејҸиҪ¬жҚўгҖӮ - christemplate <typename T> T get();
,如果您想要赋值,请考虑使用template <typename T> void assignTo( T& )
,因为这将使用户语法更友好(编译器将推断类型)。 - David Rodríguez - dribeas