Luca Luca -3 years ago 98
C++ Question

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
and call that, it is fine. Is there a way to make these two functions inambiguous?

Answer Source

The overload resolution has nothing to do with 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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download