简体   繁体   English

复制构造函数中的模板

[英]template in copy constructor

Could you please tell me why I am getting the compilation error 你能告诉我为什么我得到编译错误吗

template<class T> class 'Node' used without template parameters

with the following code 用下面的代码

template<class T>
    class Node
    {
        private:
            T _value;
            vector<Node*> children;

        public:
            Node(T value);
            Node<T>(const Node<T>& node);
            void AddChild(Node<T>* node);
            T getValue();
            vector<Node<T>*> returnChildren();
            ~Node();
    };

    template <class T>
    Node::Node<T>(T value):_value(value)
    {
    }
template <class T>
Node<T>::Node(T value):_value(value)
{
}

Try this one. 试试这个。

When you wrote 当你写

Node::Node<T>(T value):_value(value)

You have no template parameter on the class (the first Node on that line) but instead have one on the constructor (the second Node ). 您在类上没有模板参数(该行的第一个Node ),但是在构造函数上有一个模板参数(第二个Node )。 That is incorrect. 那是不对的。

In your case, Node is the template class. 在您的情况下, Node是模板类。 When you use that class, you have to use it with template parameters. 使用该类时,必须将其与模板参数一起使用。 This does not work : 这不起作用:

template <class T>
Node::Node(T value):_value(value)
{
}

Because the class Node is templated and you use it without template parameter. 因为Node类是模板化的,所以您可以不使用template参数来使用它。

This does not work neither because you put the template parameters on the function (here the constructor) not the class. 这也不起作用,因为您将模板参数放在函数(此处为构造函数)而非类上。

template <class T>
Node::Node<T>(T value):_value(value)
{
}

This does work. 这确实有效。

template <class T>
Node<T>::Node(T value):_value(value)
{
}

You use this syntax only for the class, it differs when you write a function. 您仅对类使用此语法,编写函数时有所不同。

For function. 为了功能。
Let's say we have this class 假设我们有这堂课

class MyTemplate
{
    template<typename T>
    void foo(T val);
};

You may define the method like that : 您可以这样定义方法:

template<typename T>
void MyTemplate::foo<T>(T val)
{

};

But it fails. 但是失败了。 Clang prints this error : 铛打印此错误:

function template partial specialization is not allowed 功能模板不允许部分专业化

For function you don't need it, you have to write 对于功能,您不需要它,您必须编写

template<typename T>
void MyTemplate::foo(T val)
{
}

And if you want to specialize it, you can write 如果要专攻它,可以写

template<>
void MyTemplate::foo(int val)
{
}

Or 要么

template<>
void MyTemplate::foo<int>(int val)
{
}

Declaration : 宣言 :

When you declare a variable of type Node, you have to use the template parameter too. 当声明类型为Node的变量时,也必须使用template参数。

Node<int> myNode(12);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM