use*_*853 -1 c++ macros templates
我必须在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
}
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
因此,我想消除不同数据类型的重复代码...所以,我尝试使用宏,取决于枚举的值,为不同的数据类型定义相同的变量..但然后无法区分MACROS
例如
void Test(enum value)
{
#if INT
typedef int datatype;
#elif FLOAT
typedef float datatype;
.
.
.
#endif
datatype x;
// Do operation on same variable
}
Run Code Online (Sandbox Code Playgroud)
但现在每次第一个条件#if INT都成真.我试图设置不同的宏值来区分但不工作:(
任何人都可以帮助我实现上述目标.
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果你真的希望你的功能是通用的,那么模板就是你的选择.以上是从main方法中调用方法的方法.这可能对您重用不同类型的函数有所帮助.选择任何教程或C++书籍,以便完全理解模板并掌握完整的概念.干杯.
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |