user1508519
user1508519

Reputation:

How to require an explicit cast

I have the following error:

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

The reason why is because I provided a vector<int> conversion operator for PerformObj so that the results can be stored in a vector. However, the problem is, because InObj expects a vector<int> on the right hand side, it implicitly converts PerformObj, causing an issue. I would like to have it so that PerformObj can only be explicitly cast to a vector<int> (plus signs added for readability).

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

As you can see, PerformObj takes InObj as a left hand side parameter, but the addition of the conversion operator causes ambiguity.

Ideally, I would like something like this:

std::vector<int> results = static_cast<vector<int>>(x in num perform cube);

For reference, here is the code:

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;

Upvotes: 0

Views: 371

Answers (1)

Joe Z
Joe Z

Reputation: 17936

I believe the answer is right in the headline for the question: Use the explicit keyword on the type conversion operator.

More here: http://www.parashift.com/c++-faq/explicit-ctors.html

But, you need C++11. More here: Can a cast operator be explicit?

Upvotes: 2

Related Questions