有没有办法传递普通函数并调用模板函数?

时间:2021-01-17 14:52:53

标签: c++

#include<iostream>
using namespace std;

template<class T>
void display(T a){
    a += a;
    cout << "Template Function: " << a << endl;
}

template <class T1, class T2>
void display(T1 a, T2 b){
    cout << "a: " << a << endl << "b: " << b << endl;
}

void display(int x){
    cout << "Ordinary Function: " << x << endl;
}

int main(){
    display(1);  // this will call ordinary function
    display(1.2);  
    display('T');
    display(1, 2);
    display('A', 'B');
    display(2.1, 2.1);
    return 0;
}

在上面的 C++ 代码中,在 display(1) 函数调用上调用了普通函数。有什么办法可以调用模板函数而不是普通函数

2 个答案:

答案 0 :(得分:4)

你可以这样称呼它:

display<int>(1);

答案 1 :(得分:1)

调用模板函数的语法是:

<块引用>

functionName<dataType>(arg1, arg2, ...);

默认情况下,编译器会调用同名的普通函数,如果它找到完全匹配的。在这种情况下是 void display(int x)。如果你想调用模板函数,而不是它的普通版本,你需要准确地调用它的调用方式:

<块引用>

display<int>(1);