我想制作一个添加三个数字的模板功能。类型可以是int或char或string。如何添加这些然后使用相同的类型返回正确的值。示例:三个数字串{5,6,7}应该加起来为18,然后将18作为字符串返回。三个数字的字符{5,6,7}应该加起来18然后返回18作为字符。
template <class MyType>
MyType GetSum (MyType a, MyType b, MyType c) {
return (a+b+c);
}
int a = 5, b = 6, c = 7, d;
char e = '5', f = '6', g = '7', h;
string i= "5", j= "6", k= "7", l;
d=GetSum<int>(a,b,c);
cout << d << endl;
h=GetSum<char>(e,f,g);
cout << h << endl;
l=GetSum<string>(i,j,k);
cout << l << endl;
此代码适用于int,但显然不适用于char或string。我不知道如何从未知类型转换为int和back,所以我可以添加数字。
答案 0 :(得分:2)
你想要添加,好像这些项是整数,但可能是int,char或std :: string。
这意味着,首先让它们成为整数,然后转换回原始类型:
template <typename T>
T sum(T t1, T t2, T t3)
{
std::stringstream input;
input << t1 << " " << t2 << " " << t3;
int sum = 0;
int item;
while ( input >> item )
{
sum += item;
}
// at this point we have the wanted value as int, get it back in a general way:
std::stringstream output;
output << sum;
T value;
output >> value;
return value;
}
以这种方式添加char
我会有点小心。 '18'
并非完全有意义,或者可能至少取决于平台。
您需要在项目中加入<sstream>
才能使用std::stringstream
。
答案 1 :(得分:0)
您可以使用boost::lexical_cast
在整数和字符串类型之间进行转换。
template <class MyType>
MyType GetSum (MyType a, MyType b, MyType c)
{
int int_a = boost::lexical_cast<int>(a);
int int_b = boost::lexical_cast<int>(b);
int int_c = boost::lexical_cast<int>(c);
int sum = int_a+int_b+int_c;
return boost::lexical_cast<MyType>(sum);
}
如果您不允许或不希望使用boost
,请自行实现功能模板lexical_cast
(您必须实现多个模板专业化,但每个模板都很容易实现)。
答案 2 :(得分:0)
您可以实现显式转换模板函数,其中每个函数都使用模板特化实现。例如:
template <typename MyType> int ToInt (MyType);
template <> int ToInt<int> (int x) { return x; }
template <> int ToInt<std::string> (std::string x) { return std::stoi(x); }
template <> int ToInt<char> (char x) { return std::stoi(std::string(&x, 1)); }
template <typename MyType> MyType FromInt (int);
template <> int FromInt<int> (int x) { return x; }
template <> std::string FromInt<std::string> (int x) {
std::ostringstream oss;
oss << x;
return oss.str();
}
template <> char FromInt<char> (int x) {
static const std::string map("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
return map.at(x);
}
然后,GetSum()
会在参数上调用ToInt<>()
,计算总和,然后调用FromInt<>()
将值转换回原始类型:
template <typename MyType>
MyType GetSum (MyType a, MyType b, MyType c) {
int aa = ToInt(a);
int bb = ToInt(b);
int cc = ToInt(c);
return FromInt<MyType>(aa + bb + cc);
}
从this demo可以看出,对于同一个程序,输出为:
18
I
18
I
案例char
的原因是转换假设结果值可以表示为单个基数36位。