how to declare pointer to objects for non-type templates?

161 Views Asked by At

please consider the following example:

template <int N, int M>
class MyClass {
    private:
       void myFunc(void);

    public:
        void callMe(void);

    };

I need to declare a generic pointer to objects of this class. The compiler reject the following statement. What am I doing wrong? Thanks for help.

extern template<int N, int M> MyClass<N, M> *obj;

Why I'm doing this? I need to write a function that is able work with a generic instance of objects from this class, please see the example:

inline template <int N, int M> void MyClass<N,M>::MyFunc(void) { obj = this; };

This is the behaviour I want, if possible. Notice that it works perfectly with NON TEMPLATE types.

void ThisIsAnotherFunction(void) {
    obj->callMe();
}
3

There are 3 best solutions below

2
On

Your different template classes will have nothing in common. What you can do is have your templated classes share a common base class, something like this:

struct BaseClass {};

template <int N, int M>
class MyClass : BaseClass {
    /*stuff*/
};

extern BaseClass* obj;

If you want a pointer to a specific concrete type, you have no choice but to provide values for N and M in your declaration.

extern MyClass<2, 3>* obj2;
0
On

Your question allows at least two interpretations...

I) ...you want runtime polymorphism

Different instantiations of the same template are completely unrelated types. If you want them to share a common interface you can use a common base class:

struct base {
    /* declare common interface here */
};

template <int N, int M> struct foo : base {};

II) ... you want a variable obj for each instantiation of the tempalte

This smells like singleton and I am not sure if it makes any sense to do that, but that would be something like:

template <int N,int M> struct foo {
    constexpr static const foo* obj = new foo();    
};
0
On

For the records, I resolved by using the suggestion wrote by #user463035818 (thanks dude!). I created a base class with callMe as virtual function (refer to initial example). Thanks to all that provided their support. Hope to retribute soon.