另外这种情况下如何设置参数缺省值呢?

比如 template <typename T> void func(T a){...}, 我要根据参数a是数值还是字串采取不同行动,那如何可靠而简单地判断输入的参数是数值还是字串? 

aluckdog
浏览 66回答 2
2回答

尚方宝剑之说

既然你已经知道对每一种类型所采取的行动了,那就自己写重载函数咯。#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;}

红糖糍粑

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;}
打开App,查看更多内容
随时随地看视频慕课网APP