Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

c++ - Static member variable in template, with multiple dlls

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There exists the following solution, as well:

  • in the library: explicitly instantiate some template specialization and share them with dllexport
  • in the main program:
    • if the specialization is available it will be used from the library
    • if the specialization is not available it is compiled in the main program

The desciption in detail how you can do this:

Anteru's blog Explicit template instantiation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...