C++模板函数的实参类型如何判断呢?

2025-03-01 11:47:43
推荐回答(2个)
回答1:

既然你已经知道对每一种类型所采取的行动了,那就自己写重载函数咯。

#include
#include
#include

using namespace std;
//3个action,不同的重载函数
void action( int var )
{
cout << "this is a integer" << endl;
}

void action( string& var )
{
cout << "this is a string" << endl;
}

template
void action( vector var )
{
cout << "this is a vector" << endl;
}

//根据模板推导出不同的类型而调用不同的action函数
template
void func(T a)
{
action( a );
}

int main( void )
{
int x = 1;
string y = "xyz";
vector z;
func(x);
func(y);
func(z);

return 0;
}

回答2:

template void func(T c);
templater <> void func(int c) {
// do sth with T = int;
}

templater <> void func(std::string c) {
// do sth with T = std::string;
}