Static member variable in template, with multiple dlls

后端 未结 7 951
不思量自难忘°
不思量自难忘° 2020-12-15 19: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

7条回答
  •  情书的邮戳
    2020-12-15 20:00

    There appears to be a way to do this with fewer limitations for the code that uses the template class.

    Make the static member a pointer. Create a global map which has fixed known type and can be exported from the DLL. The map uses the typeid() of the class as key and the address of the "global variable per class" as value. Initialise the static member through a function that tests whether the class already exists in the map and if so forces the second version of the class (in the second DLL) to point to the static variable of the first version of the class.

    In this way every DLL has a distinct static object, but every DLL also has a pointer and all the pointers point to the same one of the static objects.

    Here's some pseudo-code, assuming the static's type is the same as the template parameter (but should be easily adapted for other cases).

    map dllexport the_map;  // instantiate this once in a single DLL
    
    T *set_the_global(T *candidate) {
      map::iterator r = the_map.find(string(typeid(the_class).name()));
      if(r == the_map.end()) {
        the_map[string(typeid(the_class).name())] = (void*)candidate;
        return candidate;  // new class: use it as global storage location
      } else {
        return (T*)(r->second);  // class already has global storage location
      }
    }
    
    template  class the_class {
      virtual void something();  // so RTTI exists
      static T *the_global;  // use this! always points to the same object
      static T one_per_dll;  // only used in initialisation
    };
    template the_class::one_per_dll;
    template the_class::the_global = set_the_global(&the_class::one_per_dll)
    

提交回复
热议问题