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

徘徊边缘 提交于 2019-12-19 19:47:02

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/12525012/c-specializing-member-requires-template-syntax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!