Search code examples
c++templates

How to set static member variable of template class


I have a template class with a static member, but I am not sure how to set the static member variable outside of the class at runtime. Here is an example:

header.h

#ifndef HEADER_H
#define HEADER_H

template <typename T>
struct A {
  static int x;
};

template <typename T>
int A<T>::x = 7;

#endif

main.cpp

#include "header.h"

int main(int argc, char **argv) {
  // A<>::x = 8; // Want something like this to work for all template types
}

The only thing I got to work is to set it for all possible template types, e.g:

A<int>::x = 8;
A<uint8_t>::x = 8;
A<float>::x = 8;
...

but the issue is that in my code, the list of all possible types for T is very long. Is there a better solution? I could obviously just make the member not static and set it from a constructor, but the uses of the struct in my code is very deeply buried and it would not be ideal to do it that way.


Solution

  • If you have data that doesn't depend on the template parameters, I suggest that you add a non-template base that has those members:

    #ifdef AHEADER
    #define AHEADER
    struct ABase
    {
      static int x;
    };
    template<typename T>
    struct A : ABase
    {
       ...
    };
    #endif
    #include <aheader.hpp>
    int ABase::x = 8;
    ...
    void some_func()
    {
      ABase::x = 10;
    }
    

    This will not work, however, if the variable ever needs to track different values for different template types.