C ++:专业成员需要«template<>»语法 [英] C++: specializing member requires «template<>» syntax

查看:268
本文介绍了C ++:专业成员需要«template<>»语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做错了什么?

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

谢谢。

推荐答案

静态成员的定义由编译器解释为一种特殊化(实际上,它是一种特殊化:你正在给出一个声明, T = int )。这可以通过在定义之前添加 template<> 来修复。

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.

在模板中定义静态成员有点一个bummer:静态成员需要定义在header之外,这是可能的,只有当你已经知道所有可能的 T 您的binder。

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.

例如,现在你正在为 T = int 定义它。现在,如果你开始使用 Binder< double> 某处,静态成员将是一个未定义的引用。

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.

这篇关于C ++:专业成员需要«template&lt;&gt;»语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆