【发布时间】:2012-05-24 18:16:32
【问题描述】:
给定以下程序:
#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 来处理这种情况?
【问题讨论】:
-
隐式转换是一个很好的麻烦来源。重新考虑你是否真的想要这个......
-
我愿意。在这一点上,出于好奇,我对此最感兴趣。
-
您也可以在 C++11 中使用
explicit operator int()等。这可以防止错误,就像使用getType()函数一样,因为用户必须显式转换。 -
在您的评论的早期版本中,您声称您只想为赋值和初始化执行此操作,并询问是否可以将转换限制为这两个操作。他们不能。这是转换问题的一部分,它们会在您可能不希望它们发生的情况下发挥作用。您还包括了替代
template <typename T> T get();,好吧,如果您想要assignment,请考虑template <typename T> void assignTo( T& ),因为这将使用户语法更友好(编译器将推断类型) -
大卫,感谢您的关注,我在考虑您刚刚试图澄清的内容后编辑了我的评论。我觉得您正在投入大量精力来试图驳回一个有效的问题。无论如何,应用程序对您来说有什么关系?我问了一个简洁的问题,我正在寻找一个简洁的答案。
标签: c++ string implicit-conversion overload-resolution conversion-operator