简体   繁体   English

将类型参数传递给自引用指针

[英]Passing type parameter to self-referential pointer

template <class T>
class Node {
    private:
        T m_value;
        //Node* m_ptr;    //(1)
        //Node<T>* m_ptr; //(2)
};

Can someone explain what is the difference between the above two statements (1) and (2)? 有人可以解释上述两个陈述(1)和(2)之间的区别吗? Both statements seem to compile, but I can't seem to find what the ISO C++ says about them. 这两个语句似乎都在编译,但我似乎无法找到ISO C ++对它们所说的内容。

They are the same thing, because you declare the pointer inside the template, thus when you create an instance of Node the compiler knows what T is. 它们是相同的,因为您在模板中声明了指针,因此当您创建Node的实例时,编译器知道T是什么。 You don't have to specify the type for a template if it can be deduced, eg from argument types, or in this case from the template instance the pointer belongs to. 如果可以推导出模板的类型,则不必指定模板的类型,例如,从参数类型,或者在这种情况下,指针所属的模板实例。

template <class T>
class Node {
public:
    T m_value;
    Node* m_ptr;    //(1)
    //Node<T>* m_ptr; //(2)
};

int main()
{
    Node<float> test;
    test.m_ptr = new Node<float>{}; // valid
    test.m_ptr = new Node<bool>{};  // invalid - triggers compiler error
    auto val = test.m_ptr->m_value; // val will be of float type
}

According to the C++ Standard (14.6.1 Locally declared names) 根据C ++标准(14.6.1本地声明的名称)

3 The injected-class-name of a class template or class template specialization can be used either as a template-name or a type-name wherever it is in scope. 3类模板或类模板特化的inject-class-name 可以用作模板名称或类型名称,只要它在范围内。 [ Example: [例如:

template <class T> struct Base {
Base* p;
};
template <class T> struct Derived: public Base<T> {
typename Derived::Base* p; // meaning Derived::Base<T>
};
template<class T, template<class> class U = T::template Base> struct Third { };
Third<Base<int> > t; // OK: default argument uses injected-class-name as a template

— end example ] - 结束例子]

Thus these data member declarations 因此这些数据成员声明

Node* m_ptr;    //(1)
Node<T>* m_ptr; //(2)

are equivalent because the injected class name Node is used in the scope of the class definition. 是等价的,因为注入的类名称Node用在类定义的范围内。

They are "the same" 他们是一样的”

I think that's what it is happening is, in the case of 我认为这就是它发生的事情

Node* m_ptr_n 节点* m_ptr_n

The compiler makes the type match the class type. 编译器使类型与类类型匹配。

In the case of 如果是

Node < T>* m_ptr Node <T> * m_ptr

What it's created is a pointer to a class witch template matches with the "T" type. 它创建的是一个指向类巫婆模板与“T”类型匹配的指针。

If you want to get an int instance that points to a float instance what you can do is pass both types to the template. 如果要获取指向float实例的int实例,可以将两种类型都传递给模板。

template <class T1, class T2, class T3>
    class Node {
    public:
         T1 m_value;
         // Node* m_ptr_n;    //(1)
         Node<T2, T3>* m_ptr; //(2)
    };

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

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