简体   繁体   English

c ++函数名称歧义

[英]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. 如果我将第二个方法重命名为transpose2并调用它,那很好。 Is there a way to make these two functions inambiguous? 有没有办法让这两个函数变得模糊不清?

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. 您必须使被调用的对象成为const ,以使const成员函数重载被调用。 eg 例如

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

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". 在你的情况下,你已经在“const”的基础上进行了上传。 So second function will be called if you declare d as const otherwise the first version will be called. 因此,如果将d声明为const,则将调用第二个函数,否则将调用第一个版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM