[英]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.