不同数据类型的相同变量?

时间:2013-12-11 11:25:14

标签: c++ templates macros

我必须在c ++中调用一个具有不同数据类型的简单函数。例如,

void Test(enum value)
{
      int x;
      float y; // etc
      if(value == INT)
      {
         // do some operation on x

      }
      else if(value == float)
      {
         // do SAME operation on y
      }
      else if(value == short)
      {
         // AGAIN SAME operation on short variable
      }
      .
      .
      .
}

因此我想消除不同数据类型的重复代码...... 所以,我尝试使用宏,取决于枚举的值,为不同的数据类型定义相同的变量..但后来无法区分MACROS

e.g。

void Test(enum value)
{
      #if INT 
       typedef int datatype;
      #elif FLOAT 
       typedef float datatype;
      .
      .
      .
      #endif

      datatype x;

      // Do operation on same variable

}

但现在每次第一个条件#if INT都变为现实。 我试图设置不同的宏值来区分但不起作用:(

任何人都可以帮助我实现上述目标。

3 个答案:

答案 0 :(得分:6)

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

//type generic method definition using templates
template <typename T> 
void display(T arr[], int size) {
    cout << "inside display " << endl;
    for (int i= 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}


int main() {

    int a[10];
    string s[10];
    double d[10];
    for (int i = 0; i < 10; i++) {
        a[i] = i;
        d[i] = i + 0.1;
        stringstream std;
        std <<  "string - "<< i;
        s[i] = std.str();
    }
    display(a, 10); //calling for integer array
    display(s, 10); // calling for string array
    display(d, 10); // calling for double array
    return 0;
}

如果你真的希望你的功能是通用的,那么模板就是你的选择。以上是从main方法中调用方法的方法。这可能对您重用不同类型的函数有所帮助。选择任何教程或C ++书籍,以便完全理解模板并掌握完整的概念。欢呼声。

答案 1 :(得分:3)

您可以使用模板来达到目的。

只需编写一个模板函数,该函数将函数参数中的值作为泛型类型并将操作逻辑放入其中。现在使用不同的数据类型调用函数。

答案 2 :(得分:0)

我建议你使用函数重载:

void foo(int arg) { /* ... */ }
void foo(long arg) { /* ... */ }
void foo(float arg) { /* ... */ }

假设您想要对整数和长类型执行相同的操作,您可以通过这种方式消除代码重复:

void foo(long arg) { /* ... */ }
void foo(int arg) { foo((long) arg); }
相关问题