[英]How can I convert between types in a template and back to the original type
我想制作一个添加三个数字的模板功能。 类型可以是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,所以我可以添加数字。
您想要添加,就好像项目将是整数,但可能是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
。
您可以使用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
(你必须实现几个模板特化,但每个模板都很简单)。
您可以实现显式转换模板函数,其中每个函数都使用模板特化实现。 例如:
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);
}
从本演示中可以看出,对于同一个程序,输出为:
18
I
18
对于char
情况, I
的原因是转换假定结果值可以表示为单个基数36位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.