Luca
Luca

Reputation: 10996

c++ function name ambiguity

My class has two functions with the same name and the following signature:

Mat<T, rows, cols> & transpose()
{   
    for (size_t i = 0; i < rows; ++i) {
        for (size_t j = i + 1; j < cols; ++j) {
            std::swap(at(i, j), at(j, i));
        }
    }
    return *this;
}

This method does an inplace transpose of the matrix. Now, I have another function which leaves the original matrix unchanged and does the transpose in a new matrix. The signature is:

Mat<T, cols, rows> transpose() const

Note that the columns and rows are swapped.

Now, I call it as:

Mat<int, 3, 4> d;
// Fill this matrix
Mat<int, 4, 3> e = d.transpose();

This still tries to call the first method. If I rename the second method to transpose2 and call that, it is fine. Is there a way to make these two functions inambiguous?

Upvotes: 2

Views: 408

Answers (2)

songyuanyao
songyuanyao

Reputation: 172924

The overload resolution doesn't depend on the return value, it's determined by that which function whose parameters match the arguments most closely. You have to make the object being called on to be const, to make the const member function overload to be called. e.g.

Mat<int, 4, 3> e = const_cast<const Mat<int, 3, 4>&>(d).transpose();

Upvotes: 7

Geek
Geek

Reputation: 283

You can't overload function by return type.Discussed in below thread

Is it possible to have different return types for a overloaded method?

In your case, you have overloded on the basis of "const". So second function will be called if you declare d as const otherwise the first version will be called.

Upvotes: 4

Related Questions