为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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 关注
  • 65 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信