我有以下错误:
error: use of overloaded operator '+' is ambiguous (with operand types 'InObj' and 'class PerformObj')
之所以如此,是因为我为vector<int>
提供了PerformObj
转换运算符,以便将结果存储在向量中。但问题是,因为InObj
在右侧需要vector<int>
,它会隐式转换PerformObj
,从而导致问题。我想拥有它,以便PerformObj
只能显式地转换为vector<int>
(为了便于阅读而添加了加号)。
x is an integer
nums is a vector<int>
cube is a lambda
((x + in + nums) + perform + cube)
^inobj ^ implicitly converted to vector<int>
^performobj
正如您所看到的,PerformObj
将InObj
作为左侧参数,但添加转换运算符会导致歧义。
理想情况下,我想要这样的事情:
std::vector<int> results = static_cast<vector<int>>(x in num perform cube);
供参考,以下是代码:
InObj& operator+(InObj& lhs, const std::vector<int>& rhs) {
lhs.rhs = rhs;
return lhs;
}
class PerformObj {
public:
// snip
operator std::vector<int>() const {
std::vector<int> temp;
for (int i = 0; i < lhs.rhs.size(); i++) {
temp.push_back(rhs(lhs.rhs[i]));
}
return temp;
}
friend std::ostream& operator<<(std::ostream& os, const PerformObj& po);
} performobj;
PerformObj& operator+(const InObj& lhs, PerformObj& rhs) {
rhs.lhs = lhs;
return rhs;
}
// Error occurs on the following line
std::cout << x in nums perform cube << std::endl;
答案 0 :(得分:2)
我认为答案正好在问题的标题中:在类型转换运算符上使用explicit
关键字。
更多信息:http://www.parashift.com/c++-faq/explicit-ctors.html
但是,你需要C ++ 11。更多信息:Can a cast operator be explicit?