【问题标题】:Same variable for different datatypes?不同数据类型的相同变量?
【发布时间】:2013-12-11 11:25:13
【问题描述】:

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

例如

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

      datatype x;

      // Do operation on same variable

}

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

谁能帮我实现上述目标。

【问题讨论】:

  • 你需要#ifdef吗?
  • 你不能将你的函数命名为 main。
  • 你能说得更具体一点吗:你想通过枚举值切换还是想为不同的 arg 类型编写相同的代码?
  • 我们在这里谈论的究竟是什么重复代码(为了更好地理解您的问题)?

标签: c++ templates macros


【解决方案1】:
#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++ 书籍,以全面了解模板并掌握完整的概念。干杯。

【讨论】:

  • 你可以改用template&lt;typename T, int N&gt; void display (std::array&lt;T, N&gt;);显式大小作为第二个参数使代码容易出错并且是 C 时代的遗留物。
  • 当然巴特克。听起来很棒。谢谢。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    我建议你使用函数重载:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多