2013-12-11 32 views
-1

我必须在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

eg

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

     datatype x; 

     // Do operation on same variable 

} 

但现在每当第一个条件#if INT变为真时。 我试图设置的宏观不同的值来区分,但不工作:(

谁能帮我实现上述的事情。

+0

你需要'#ifdef'? –

+1

您不能将您的功能命名为主要功能。 –

+0

你能更具体一点:你想通过枚举值切换,还是你想为不同的参数类型编写相同的代码? – nyrl

回答

3

您可以使用模板来实现你的目的。

只需编写模板这需要在函数的参数,它是通用型的值,并把业务逻辑里面的功能。现在,调用函数与不同的数据类型。

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

如果你真的想你functi在通用时,模板就是要走的路。以上是从main方法中调用方法的方法。这可能有助于您为不同类型重用函数。拿起任何教程或C++书籍,以全面了解模板并掌握完整的概念。干杯。

+1

你可以把'template void display(std :: array )'代替;显式大小作为第二个参数使得代码容易出错,并且是C时代的遗留问题。 –

+0

当然Bartek。听起来很棒。谢谢。 – sakthisundar

0

我建议你使用函数重载:

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

假如你想要做的整数和long类型相同的操作就可以消除这样的代码重复:

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