函数模板问题

在笔试过程中遇到函数模板问题,记录问题并给出解答。

问题:

下面代码会执行什么结果:

#include<iostream>

using namespace std;

template <typename T>

void print(T t){

    cout<<"Template:"<<t<<endl;
}

void print(int i)
{
    cout<<"int:"<<i<<endl;
}


int main()
{
    print(10);
    print(10.0);
    return 0;

}

结果:

int:10
Template:10

上面代码的主要问题是,调用print函数时函数模板和非模板函数的如何调用问题。

解答:

首先,一个非模板函数可以和一个同名的函数模板同时存在。

然后,对于非模板函数和同名函数模板,如果其他条件都相同,在调用时会优先调用非模板函数而不是从该模板产生处一个实例。如果做特殊定义可以实现有限调用模板。

 

使用显示调用模板函数,会使得有限调用模板函数。具体代码:

#include <iostream>
using namespace std;

template <typename T>
void print(T t) {
    cout << "Template:" << t << endl;
}

void print(int i) {
    cout << "int:" << i << endl;
}

int main() {
    print<int>(10); // 显式调用模板函数,输出 "Template:10"
    print(10.0);    // 调用模板函数,输出 "Template:10"
    return 0;
}

 

参考文献:

https://blog.csdn.net/weixin_47257473/article/details/128317603

https://www.runoob.com/cplusplus/cpp-templates.html

 

来源链接:https://www.cnblogs.com/LJianYu/p/18678670

请登录后发表评论

    没有回复内容