亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

另外這種情況下如何設置參數缺省值呢?

另外這種情況下如何設置參數缺省值呢?

C++
aluckdog 2023-02-17 17:13:06
比如 template <typename T> void func(T a){...}, 我要根據參數a是數值還是字串采取不同行動,那如何可靠而簡單地判斷輸入的參數是數值還是字串? 
查看完整描述

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;
}



查看完整回答
反對 回復 2023-02-20
?
紅糖糍粑

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;
}

查看完整回答
反對 回復 2023-02-20
  • 2 回答
  • 0 關注
  • 102 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號