1

I have two base abstract classes A, and B what is inherited from A. B contains a map argument with generic type, and I would like to create children from A and B and store that in a deque:

class A {
};

template <typename T>
class B : public A {
    std::map<const char *, T> data;
    virtual void doEvent(const char *) = 0;
};

class C : public A {
};

class D : public B<char> {
    void doEvent(const char *event) {
        // use map<const char*, char>
    }
};

class E : public B<int> {
    void doEvent(const char *event) {
        // use map<const char*, int>
    }
};

std::deque<A *> as;

void main() {
    for (auto &it : as) {
        //if (it instanceof B) {
            // cast it to B
            // call B.doEvent("myEvent")
        //}
    }
}

Could somebody help me how to check that a child is inherited from B , ignoring T type. How could I use std::is_base_of or dynamic_cast with generic type.

Thanks

almasif
  • 43
  • 4
  • 3
    You could make `B` inherit from a special non-template tag type that only `B` inherits from. Then you can check if your type inherits from that type instead. – François Andrieux Jan 23 '19 at 16:51
  • 2
    @FrançoisAndrieux You should make that an answer. That gives the OP a solution that works at compile time and run time. – NathanOliver Jan 23 '19 at 17:05
  • The necessity of needing to cast to sub class is a hint that your design possibly is flawed - and we are possibly discussing an [XY-Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Maybe you want to share a bit more of information what you *actually* intend to achieve? There might be a better solution at a higher level... – Aconcagua Jan 23 '19 at 17:15
  • 1
    I do not agree on duplicate: Base class in question is not a template, linked question is a compile-time only solution (but we rely on run-time here, as unable to know at compile time of which types the elements in the deque actually are) and we are searching in opposite direction: not interested in base class(es), but if given object is an instance of one of a set of derived types (all possible template instantiations). Citing @NathanOliver's comment to (now deleted) answer: *'How would you use this to check if the A\* in the vector is a B?'* – Aconcagua Jan 23 '19 at 17:29
  • Someone please notify me if this question reopens and I will make an answer based on my comment. I don't feel comfortable reopening myself with the intention of answering as it seems like a conflict of interest (I might be biased towards disagreeing with the duplicate). I'd first like someone else to pass judgement on this duplicate close. – François Andrieux Jan 23 '19 at 18:19
  • 1
    I could't solve it yet, so I've upgraded my example. I would be grateful if somebody can help me. – almasif Jan 25 '19 at 16:57

0 Answers0