简体   繁体   English

如何在模板中的类型之间转换回原始类型

[英]How can I convert between types in a template and back to the original type

I am wanting to make a template function that adds three numbers. 我想制作一个添加三个数字的模板功能。 The type may be int or char or string. 类型可以是int或char或string。 How can I add these then return the correct value using the same type. 如何添加这些然后使用相同的类型返回正确的值。 Example: three strings of numbers {5,6,7} should add up to 18 then return 18 as a string. 示例:三个数字串{5,6,7}应该加起来为18,然后将18作为字符串返回。 three chars of numbers {5,6,7} should add up to 18 then return 18 as a char. 三个数字的字符{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;

This code works for int but obviously not for char or string. 此代码适用于int,但显然不适用于char或string。 I am not sure how to convert from an unknown type to int and back so i can add the numbers. 我不知道如何从未知类型转换为int和back,所以我可以添加数字。

You want addition as if the items would be integers though may be int, char or std::string. 您想要添加,就好像项目将是整数,但可能是int,char或std :: string。

That means, first get them to be integers, then convert back to the original type: 这意味着,首先让它们成为整数,然后转换回原始类型:

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;
}

I'd be a bit careful with the addition of char s in that way. 以这种方式添加char会让我有点小心。 '18' isn't exactly meaningful afaik, or probably at least platform dependent. '18'并非完全有意义,或者至少可能取决于平台。

You'll need to include <sstream> in your project to use std::stringstream . 您需要在项目中包含<sstream>以使用std::stringstream

You can use boost::lexical_cast to convert between integer and string types. 您可以使用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);
}

If you are not allowed, or don't want, to use boost , just implement the function template lexical_cast yourself (you will have to implement several template specializations, but each individual one is easy). 如果你不允许或不想使用boost ,只需自己实现函数模板lexical_cast (你必须实现几个模板特化,但每个模板都很简单)。

You can implement explicit conversion template functions, where each is implemented with template specialization. 您可以实现显式转换模板函数,其中每个函数都使用模板特化实现。 For instance: 例如:

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);
}

Then, the GetSum() would call ToInt<>() on the arguments, compute the sum, and then call FromInt<>() to convert the value back to the original type: 然后, 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);
}

As can be seen in this demo , for your same program, the output is: 本演示中可以看出,对于同一个程序,输出为:

18
I
18

The reason for I for the char case is that the conversion assumes the resulting value can be expressed as a single base 36 digit. 对于char情况, I的原因是转换假定结果值可以表示为单个基数36位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在模板类型之间转换? - Convert between template types? 如何将元组 &lt;&gt; 剥离回可变参数模板类型列表? - How do I strip a tuple<> back into a variadic template list of types? 我可以将模板转换/转换为其他模板类型吗? - Can I cast/convert templates to other template types? 如何为具有特定类型特征的所有类型编写函数模板? - How can I write a function template for all types with a particular type trait? 如何在C ++中转换类型? - How can I convert types in C++? 如何使用静态多态在 int 和指针类型之间进行转换? - How can I use static polymorphism to convert between int and pointer types? 如何将模板与SURF的原始图像匹配? - How can I match a template with the original image by SURF? 我可以将引用类型传递给模板以指定以下非类型模板参数的类型吗? - Can I pass a reference type to a template to specify following non-type template parameters' types? 如何将可变参数函数模板中的每个参数转换为另一种类型并获取其地址? - How can I convert each parameter in a variadic function template to another type and obtain its address? 如果我也有原始代码,如何将 wasm 转换回 C++ - How to convert wasm back to C++ if I also have the original code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM