C++: specializing member requires «template<>»

2019-02-22 18:10发布

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.

标签: c++ static g++
1条回答
Ridiculous、
2楼-- · 2019-02-22 18:45

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.

查看更多
登录 后发表回答