Search code examples
c++templatesstaticinline

Why in a C++ template, declaring a vector<T> member variable as static will produce linker error but inline static will not?


I cannot explain the following (using C++20 rules)

//FooTemplate.h
template<typename T>
class FooTemplate {
private:
   static std::vector<T> t; //linker error.
   //inline static std::vector<T> t; --> will not produce linker error
   //static T t; -->this works also with the appropriate changes in the following code
public:
    static void setT(T t1)
    {
        t.push_back(t1);
    }
    static T getT(int i)
    {
        return t.at(i);
    }
};
//main.cpp
#include"FooTemplate.h"
int main() {
  FooTemplate<Foo>::setT(Foo{});
  FooTemplate<Foo>::getT(0);
}

I have to inline the static member t in order for it to work. If I do not use a templated container (e..g define T t instead of vector<T> t it also works.

Any idea?


Solution

  • Static members must be defined (initialized) outside their class.

    Simply write in your implementation:

    template<class T> std::vector<T> FooTemplate<T>::t = [some initializer];
    

    EDIT: You do not actually need to explicitely initialize them (unless they are objects of a class without a default constructor), but you do need to repeat their declaration like this anyway.