Static member variable in template, with multiple

2020-02-09 06:44发布

My code is built to multiple .dll files, and I have a template class that has a static member variable.

I want the same instance of this static member variable to be available in all dlls, but it doesn't work: I see different instance (different value) in each of them.

When I don't use templates, there is no problem: initialize the static member in one of the source files, and use __declspec(dllexport) and __declspec(dllimport) directives on the class. But it doesn't work with templates. Is there any way to make it work?

I saw some proposed solutions that use "extern", but I think I can't use it because my code is supposed to work with visual studio 2002 and 2005.

Thank you.

Clarification: I want to have a different instance of static variable per each different type of template instantiation. But if I instantiate the template with the same type in 2 different dlls, I want to have the same variable in the both of them.

7条回答
一夜七次
2楼-- · 2020-02-09 07:45

There are two fixes for this problem which I can see.

First is that you use another class, one that is not a template, to hold this static value - or make it a global? - and export that out of the dll.

The other is slightly mor complicated in that you instantiate the template in the code and export that instantiated templated value(s). So to give an example say I had a special kind of linked list templated class and needed to have a static value shared across the DLL's. I wrote the code to be templated but it is only really used for some small number of types. I would instantiate the classes as such:

template <class T> class Foo;
template<> class Foo<int> {};

Then you could export the static variables contained within.

__declspec(dllexport) int Foo<int>::StaticMember = 0;

(Or something like that, I'm a bit rusty with doing dll export/import.)

Though the real question is why would you want to do this, as technically a DLL can be used across processes with only one copy stored in memory. Do you really want there to only be one version of the static for all processes, or one per process?

查看更多
登录 后发表回答