When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
27 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
You can't. Arrays are of a fixed type, can't have an array with different types. There are various workarounds. One way is to make 2 arrays, one for Children and one for Parents and then iterating over both. Another way is to make an std::array<std::unique_ptr<Child>>.
I'm not trying to make an array that has more than one type
I'm trying to make an init function that would work for either
Make 2 functions and rely on overloading. For the user it will look like init can take both Parent and Child pointers.
There are also ways to de-duplicate the code should that be necessary.
like what
Like factoring the inside, arr[i].a = 0; in this case, into a separate function, say void handle(Child *c);
Doesn't seem worth it in the example case because the inside is so small.
Another way is to make init a template and restrict its input to Child * and Parent *.
I thought about using templates, is there a downside to that?
It's more messy than using an overloaded function for this case.
You don't actually need the flexibility because the set of types is known.
And users can be dumb and explicitly use init<Child*>(parents, std::size(parents));
okay
The standard library would use a pair of iterators here.
I find that ugly, but it's flexible and works.
what do you mean?
template <class Iterator>
void init(Iterator begin, Iterator end) {
while (begin != end) {
begin->a = 0;
}
}
init(std::begin(arr), std::end(arr));
This works for both Parent[] and Child[].
Semi off topic but another way is to make a constructor
If there aren't many ways to "init", that actually works rather well
If for whatever reason you need the two step
Technically there's a way to accept only builtin arrays, if you're dealing with those only, but if you start having dynamically allocated objects/arrays, that can be inconvenient in multiple ways
Probably the main reason why the constructor is preferred, is to make it impossible to forget to call "init"
@vapid kelp
Please don't delete forum posts. They can be helpful to refer to later and other members can learn from them. In the future you can use !solved to close a post and mark a post as solved.
!solved