-1

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?

user2465039
  • 894
  • 1
  • 11
  • 28

1 Answers1

1

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.

IWonderWhatThisAPIDoes
  • 1,000
  • 1
  • 4
  • 14