0

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?

Fault
  • 420
  • 3
  • 17
  • 3
    No, C++ doesn't have [introspection](http://en.wikipedia.org/wiki/Type_introspection) so there is no way to get structure members of unknown structures. – Some programmer dude Mar 05 '14 at 17:18
  • I think you don't need introspection, compile-time reflection is what's needed here. And that can be achieved by various means, but not with "vanilla" C++. (like multi-stage builds with code generation). – Bartek Banachewicz Mar 06 '14 at 11:57

2 Answers2

0

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).

Fault
  • 420
  • 3
  • 17
-1

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.

rerun
  • 25,014
  • 6
  • 48
  • 78
  • 1
    How is the OP supposed to get all fields of the structs inside the template function/method, with the exact struct type being unknown? – Jonas Schäfer Mar 05 '14 at 17:22
  • you can duck type a set of stucts or provide an adaptor template class or overload the operator. Less is an example of a template adaptor.. – rerun Mar 05 '14 at 17:38
  • Like, duck type every possible set of every possible field type? – Bartek Banachewicz Mar 06 '14 at 11:59
  • In general the adaptor is for non conforming types. Similar to less. If you have a < operator then that is what less uses if not you can specialize less. – rerun Mar 06 '14 at 15:12