Sharing static members between template instantiations? (impossible?)

强颜欢笑 提交于 2019-12-19 05:32:52

问题


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.


回答1:


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
{
    //...
};



回答2:


Sounds like you should either just make them global and not worry about it. Perhaps using namespaces is what you want?



来源:https://stackoverflow.com/questions/3198249/sharing-static-members-between-template-instantiations-impossible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!