Is it possible to pass an unknown struct to a function and iterate through its elements? If yes, what is the simplest way to do that?
Asked
Active
Viewed 87 times
0
-
3No, that's not possible. – John Kugelman Oct 11 '21 at 14:56
-
2What you are asking for is called reflection, and C++ does not yet support that. There are libraries you can use to give you something similar though, but they required you manually register the members of all the types you want to participate in the reflection. – NathanOliver Oct 11 '21 at 14:57
-
2This is a two-part question with a two-part answer: 1) You can pass an "unknown" struct via polymorphism or templates. 2) You can iterate through its elements with the help of a library like Boost.Fusion. See https://stackoverflow.com/questions/4335170/accessing-members-in-a-c-struct-both-dynamically-and-statically for this second point. – Matt Oct 11 '21 at 15:02
-
Thanks a lot guys! This already helped much. Now I know what to look for. – El tornillo Oct 11 '21 at 15:06
1 Answers
2
The C++ solution is to pass a std::tuple
, not a struct
. You can then call std::get<I>(std::tuple)
with I running from 0 to std::tuple_size

MSalters
- 173,980
- 10
- 155
- 350