문제

Suppose I have a struct, such as:

struct Foo {
    double a;
    float b;
    int c;
};

Summing fooA and fooB (both of type Foo) would equate to:

{fooA.a + fooB.a, 
 fooA.b + fooB.b, 
 fooA.c + fooB.c};

Now my question is, could a generic function be created that would sum structs together in this manner? i.e.:

template <typename StructType>
StructType sumStructs(StructType A, StructType B) {
    // sum component with one another, return resulting struct
}

Alternatively, what limitations would you need to impose for it to be possible?

도움이 되었습니까?

해결책

As Joachim Pileborg put it,

No, C++ doesn't have introspection so there is no way to get structure members of unknown structures.

So what I ended up doing was overloading + for each struct individually. This in turn allowed me to create a generic function that takes a node, and sums all of its parent structs (useful, for example, for summing positions, to get the absolute position of an object).

다른 팁

Yes you certainly can. You can also overload the + operator and would get this type of genericism for free. There are many ideas in c++ that are like this. Less<T> or begin and end free functions.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top