Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing static members between template instantiations? (impossible?)

I am doing something that is probably silly, but it would be nice if it worked.

I am attempting to specialize types in a way that I need my own lookup structure that is essentially global (but ideally encapsulated as a class variable), but I want the objects to be type safe, so they are parameterized.

Consequently, I have, essentially

template<class T, int N>
class SpecialArray
{
//...
private:
   static map<string, internal_t> lookupTable
}

and for whatever reason, I didn't think until such time as I went to initialize lookupTable that when I say

template <class T, int N>
SpecialArray<T,N>::lookupTable;

there are going to be many different lookupTables running around attached to the various instantiations of SpecialArray.

I suspect it may just be a pipe dream and that the correct answer is just making it a separate global singleton object, but is there anyway to make it such that there is just one lookupTable for all the SpecialArrays?

Like, in the C++ in my mind (which is not real C++), this would go something like

template <class T, int N>
SpecialArray<*,*>::lookupTable;

... but sadly GCC does not compile the C++ in my mind

Is there any actual way to get what I want (somewhere in C++0x-land or something)? I am likely to run into this problem also with some static methods that manipulate this lookup table (which does not keep track of types or Ns).

... sorry if that didn't make any sense.

Thanks in advance for any help or sympathy you can render.

like image 516
OhNowISeePlusPlus Avatar asked Jul 07 '10 19:07

OhNowISeePlusPlus


1 Answers

You could add a non-templated base class and move lookupTable into that class:

class Base
{
protected:
    static map<string, internal_t> lookupTable
};

template<class T, int N>
class SpecialArray : Base
{
    //...
};
like image 162
jon-hanson Avatar answered Nov 10 '22 16:11

jon-hanson