如何将指针传递给函数的不同结构?

时间:2016-10-23 00:03:25

标签: c++ struct

使用C ++和C,我们可以通过指向void构造的指针将不同的函数传递给另一个函数。我想做同样的事情,将结构传递给一个函数,就像这个简单的例子:

#include <iostream>  
using namespace std;

struct S1 {
    static constexpr int  n=1;
    static constexpr double  v=1.2;
};
struct S2 {
    static constexpr int  n=2;
    static constexpr double  v=3.4;
};

typedef void *Vp;  // this would be (*Vp)() for functions

void func(Vp p) {
    cout << "n=" << p->n << " v=" <<'\n'
    // (fails here with error: 'Vp {aka void*}' is not
    //   a pointer-to-object type)
}
int main() {
    struct S1  s1;
    struct S2  s2;
    cout <<"main: using first data\n";
    func(&s1);
    cout <<"main: using second data\n";
    func(&s2);
    return 0;
}

有没有人知道如何使这项工作或甚至是否可能? 之前曾问过类似的问题,但答案对我没有帮助: passing different structs to a function(using void *)
我知道使用一个结构并创建不同的实例会更好,但是我已经有了一个标题,其中有很多数据以这种方式加载到结构中。

1 个答案:

答案 0 :(得分:1)

如果没有两个单独的功能,你就无法做到,但可以让编译器为你生成它们。您可以使用功能模板

template<typename StructType>
void func(StructType *p) {
    cout << "n=" << p->n << " v=" << p->v << endl;
}

现在编写func(&s1);时,编译器将根据名为func<S1>的模板为您生成一个新函数,如下所示:

void func<S1>(S1 *p) { // not real syntax
    cout << "n=" << p->n << " v=" << p->v << endl;
}

,同样适用于S2

相关问题