samedi 9 février 2019

Check for template class equality through base class pointer

Is it possible to check, through a base class pointer, whether different derived template classes are specialization of the same template class?

This is achievable through introducing an intermediate non-template base-class. However, i would like to know whether this pattern is avoidable when the sole purpose of this intermediate class is for identification:

class A{}

class B_base : public A{}

template<T>
class B : public B_base {}

// There may be other derived classes of A
template<T>
class C: public A{}

void main() {
    // ... some vector of pointers to A derived objects
    std::vector<A*> v;

    for(auto& i : v){
        // Check whether i is any specialization of B through a 
        // dynamic_cast to the intermediate class
        if(dynamic_cast<B_base*>()){
            // This is a B_base object, 
        }
    }
}

Ideally, i would like something like this, to avoid the intermediate class.

class A{}

template<T>
class B : public A{}

// There may be other derived classes of A
template<T>
class C: public A{}

void main() {
    // ... some vector of pointers to A derived objects
    std::vector<A*> v;

    for(auto& i : v){
        // Check whether i is any specialization of B
        if(templateTypeId(i) == templateTypeId(B*)){
            // This is a B object with some unknown specialization
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire