如何要求显式强制转换

How to require an explicit cast

本文关键字:转换      更新时间:2023-10-16

我有以下错误:

error: use of overloaded operator '+' is ambiguous (with operand types 'InObj' and 'class PerformObj')

原因是我为PerformObj提供了vector<int>转换运算符,以便将结果存储在向量中。然而,问题是,因为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

如您所见,PerformObjInObj作为左侧参数,但添加转换运算符会导致歧义。

理想情况下,我想要这样的东西:

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;

我相信这个问题的标题中的答案是正确的:在类型转换运算符上使用explicit关键字。

更多信息:http://www.parashift.com/c++-faq/explicit-ctors.html

但是,您需要C++11。更多内容:强制转换运算符可以显式吗?