C ++ getting dynamic generic pointer type?

the name is probably misleading, but I really did not know what to call it.

let's say I have the following structures

template <typename T>
struct SillyBase{
   void doFunnyStuff(vector<T> vec){
        dummyField = T();
        for(int i=0; i<10; i++)
            vec.push_back(dummyField++);
    }
    T dummyField;
 };

struct A : public SillyBase<char>{};

struct B : public SillyBase<float>{};

Now let us further assume that I have a pointer

ISillyBase* ptr;

which points to an object of class DECENDANT (A or B) SillyBase - however, I DO NOT KNOW which one (I just know it is either A or B);

Is there any way for me to call doFunnyStuff ()?

maybe something like:

vector<dynamic_generic_type_of(ptr)> vec;
ptr->doFunnyStuff(vec);

thank!

+3
source share
6 answers

In your example, you cannot have SillyBase*, because it SillyBaseis defined as

template <typename T> struct SillyBase {...}

So you need to specify the type ...

, vector<T> doFunnyStuff(), ... , , , vec, vector<T>&?

+1

EDIT: ISillyBase , , , vector<T>.


, SillyBase, SillyBase* ptr;

, :/

0

SillyBase *ptr; . SillyBase , , , .

, , .

0

. , 100 . ,

class SillyBaseBase
{
    public:
        void function doFunnyFunnyStuff(SillyBase<char> *)
        {
            SillyBase<char>::doFunnyStuff();
        }

        void function doFunnyFunnyStuff(SillyBase<float> *)
        {
            SillyBase<float>::doFunnyStuff();
        }

}
0

, dynamic_cast. null, .

dynamic_cast<the_template_definition>(the_template_instantiation)

, . , , :

#include <stdio.h>
class Top /* The parent class */ {
public: 
virtual ~Top() {}; // You need one base virtual function in the base class
};

template <typename T> class SillyBase : public Top {
   void doFunnyStuff(T dummyVar){
        dummyField  = dummyField + dummyVar;
    }
    T dummyField;
 };

class A : public SillyBase<char>{};
class B : public SillyBase<float>{};

int main(){
   A a;
   Top *ptr = (Top*)(&a);
   if(dynamic_cast<A*>(ptr) != NULL)
      printf("ptr is of type A*\n");
   if(dynamic_cast<B*>(ptr) != NULL)
      printf("ptr is of type B*\n");
   return 0;
}

:

ptr is of type A*
0

, , dynamic_cast. . SillyBase. , , . , , . inheireted . , , . , , .

0

Source: https://habr.com/ru/post/1727706/


All Articles