【问题标题】:C++ | Only reference variable works in function templateC++ |只有引用变量在函数模板中有效
【发布时间】:2015-12-04 22:01:55
【问题描述】:

在使用函数模板时,我只能使用引用变量作为函数参数。

下面的程序(找到两个数字之间的最小值)工作正常。

//Program to calculate minimum among two numbers
#include<iostream>
using namespace std;
template <class ttype>
//Using reference variables 
//as function parameters
ttype min(ttype& a, ttype& b)
{
    ttype res = a;
    if (b < a)
        res = b;
    return res;
}
int main()
{
    int a = 5, b = 10; 
    int mini = min(a, b); 
    cout << "Minimum is: " << mini << endl;
    return 0;
}

但是,当我改变如下功能时:

template <class ttype>
//Using normal variables 
//as function parameters
ttype min(ttype a, ttype b)
{
    ttype res = a;
    if (b < a)
        res = b;
    return res;
}

我得到编译错误。

在使用函数模板时我们应该只使用引用变量吗?

【问题讨论】:

    标签: c++ function templates


    【解决方案1】:

    minstd::min 冲突,因为你是 using namespace std;

    您可以执行以下操作来修复它,它明确表示要使用所有命名空间之外的min

    int mini = ::min(a, b);
    

    或者,去掉using,它就可以工作了。

    这两种解决方案在 gcc 上都适用于我,无论有没有 &amp;

    【讨论】:

      【解决方案2】:

      那是因为 min 与 std::min 冲突。为您的函数使用不同的名称,或者不要使用“using namespace std”,或者将您的函数放在不同的命名空间中,或者使用这个:

      int mini = ::min(a, b);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多