5

What am I doing wrong?

template<class T>
class Binder
{
public:
    static std::vector< Binder< T >* > all;
    Node<T>* from;
    Node<T>* to;
    Binder(Node<T>* fnode, Node<T>* tonode)
    {
        from = fnode;
        to = tonode;
        Binder<T>::all.push_back(this);
    }
};

std::vector<Binder<int>*> Binder<int>::all = std::vector< Binder<int>* >(); //here it is

Thank you.

Ben Usman
  • 7,969
  • 6
  • 46
  • 66

1 Answers1

7

The definition of the static member is interpreted by the compiler as a specialization (actually, it is a specialization: you are giving a declaration that is specific to T = int). This can be fixed by adding template<> before the definition.

Defining static members in templates is a bit of a bummer: the static member needs to be defined outside a header, and that is possible only if you already know all the possible T for your binder.

For instance, right now you are defining it for T=int. Now, if you start using Binder<double> somewhere, the static member is going to be an undefined reference.

jogojapan
  • 68,383
  • 11
  • 101
  • 131
sylvain.joyeux
  • 1,659
  • 11
  • 14
  • 2
    Static members for template classes can be defined in the header. – Timo Sep 21 '12 at 06:15
  • @Timo Does not seem so. I moved the template code in bla.h that I included in bla.cpp and main.cpp. I think that compilers don't know how to "unify" global variables the same way they do for inline functions doudou@demeter:~/tmp$ g++ main.cpp bla.cpp/tmp/ccdgiTrw.o:(.bss+0x0): multiple definition of `Binder::all' /tmp/ccXM1TWJ.o:(.bss+0x0): first defined here collect2: ld returned 1 exit status – sylvain.joyeux Sep 21 '12 at 06:17
  • See $3.2/5 in the standard. It specifically allows multiple definition of static data members for class templates assuming they're in different translation units. – Timo Sep 21 '12 at 06:27