2 回答

TA貢獻1788條經驗 獲得超4個贊
既然你已經知道對每一種類型所采取的行動了,那就自己寫重載函數咯。
#include<iostream>
#include<string>
#include<vector>
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 <typename Ty>
void action( vector<Ty> var )
{
cout << "this is a vector" << endl;
}
//根據模板推導出不同的類型而調用不同的action函數
template <typename T>
void func(T a)
{
action( a );
}
int main( void )
{
int x = 1;
string y = "xyz";
vector<char> z;
func(x);
func(y);
func(z);
return 0;
}

TA貢獻1815條經驗 獲得超6個贊
template <typename T> 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;
}
- 2 回答
- 0 關注
- 102 瀏覽
添加回答
舉報