不同数据类型的变量相同吗? 我必须调用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 } . . . }
因此,我想消除不同数据类型的重复代码。。。 所以,我尝试使用宏,根据enum的值,为不同的数据类型定义相同的变量。。但无法区分宏 e、 g 但是现在每次第一个条件如果INT为真。 我尝试设置宏的不同值以区分,但不起作用:不同数据类型的变量相同吗? 我必须调用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 } . . . },c++,templates,macros,C++,Templates,Macros,因此,我想消除不同数据类型的重复代码。。。 所以,我尝试使用宏,根据enum的值,为不同的数据类型定义相同的变量。。但无法区分宏 e、 g 但是现在每次第一个条件如果INT为真。 我尝试设置宏的不同值以区分,但不起作用: 有谁能帮我实现上述目标。你可以使用模板来实现你的目标 只需编写一个模板函数,它接受泛型类型的函数参数中的值,并将操作逻辑放入其中。现在使用不同的数据类型调用函数 #include <iostream> #include <string> #include
有谁能帮我实现上述目标。你可以使用模板来实现你的目标 只需编写一个模板函数,它接受泛型类型的函数参数中的值,并将操作逻辑放入其中。现在使用不同的数据类型调用函数
#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++书籍,完全了解模板,并掌握了完整的概念。干杯。我建议您使用函数重载:
void foo(int arg) { /* ... */ }
void foo(long arg) { /* ... */ }
void foo(float arg) { /* ... */ }
假设要对整型和长型执行相同的操作,可以通过以下方式消除代码重复:
void foo(long arg) { /* ... */ }
void foo(int arg) { foo((long) arg); }
您需要ifdef吗?您不能将函数命名为main。您可以更具体地说:您想按枚举值进行切换,还是想为不同的arg类型编写相同的代码?为了更好地理解您的问题,我们在这里讨论的确切代表代码是什么?您完全可以使用模板void display std::array;显式大小作为第二个参数使代码容易出错,并且是C时代的遗物。听起来很棒。谢谢
void foo(long arg) { /* ... */ }
void foo(int arg) { foo((long) arg); }