【问题标题】:Template Function to Return Greater value in C++ [closed]在 C++ 中返回更大价值的模板函数 [关闭]
【发布时间】:2015-04-02 05:23:02
【问题描述】:

我希望能够返回两个值中的较大者,无论是整数、双精度还是类。我已经为要使用的类重载了比较运算符。该函数主要给我链接器错误。代码如下:

template <typename tType>
void returnGreater(tType &A, tType &B)
{
    if(A > B)
    {
        cout << "A is greater"; //testing
        return A;
    }
    else
    {
        cout << "B is greater"; //testing
        return B;
    }
}

【问题讨论】:

  • 请致电std::max
  • 可能duplicate?
  • 不是重复的。这涉及模板及其实际实现,而不是它们的实现位置。
  • ...链接器错误是?

标签: c++ function templates overloading


【解决方案1】:

更改返回类型。

template <typename tType>
tType& returnGreater(tType &A, tType &B)
^^^^^^ void is not the right return type for what you want to do.

PS 当您同时使用const 和非const 参数时,上述函数将不起作用。您必须弄清楚如何解决该问题。

例如,你不能使用:

int i = 10;
int j = returnGreater(i, 20);

您可以使用显式类型来实现这一点:

int j = returnGreater<int const>(i, 20); // OK.

【讨论】:

  • 谢谢。它仍然无法正常工作。我收到链接器错误,当我尝试传递整数时,我收到匹配的函数调用错误
  • @VectorCroc,MCVE 将有助于诊断问题。
【解决方案2】:

检查一下……

#include <iostream>

using namespace std;

template <typename tType>
tType& returnGreater(tType &A, tType &B){

    if(A > B)
    {
        cout << "A is greater"; //testing
        return A;
    }
    else
    {
        cout << "B is greater"; //testing
        return B;
    }
}

int main(){

    int a,b;
    cin>>a>>b;
    cout<< returnGreater(a,b)<<endl;
    return 0;

}

您的返回类型不正确。

【讨论】:

    猜你喜欢
    • 2016-12-22
    • 2012-03-23
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    相关资源
    最近更新 更多