gpt4 book ai didi

c++ - 函数模板重载

转载 作者:行者123 更新时间:2023-11-30 00:36:35 25 4
gpt4 key购买 nike

考虑以下程序。

#include <iostream>
using namespace std;

int sum (int & a, int & b)
{
cout <<" NOn template function "<<endl;
return a+b;
}

template <typename T>
int sum ( const T & a, const T & b)
{
cout<<"Template Generated .."<<endl;
return a+b;
};


int main(int argc, char ** argv)
{
cout <<sum(10,20)<<endl;;
}

问题是什么:

我期待调用非模板函数的 sum()。但是在我的输出中调用模板初始化函数。它不是函数模板重载的一部分。

请指出我在这里犯了什么错误?

最佳答案

I was expecting the sum() of non template function to be invoked.

您传递的是右值,它不能绑定(bind)到非常量引用。因此选择模板版本。

int &更改为int const & OR int,将选择第一个版本:

希望对您有所帮助。

关于c++ - 函数模板重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15738003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com