"模板<class>好友类 Foo"是什么意思?

What does `template <class> friend class Foo` mean?

本文关键字:Foo 是什么 意思 gt 模板 lt class 好友      更新时间:2023-10-16

我正在探索boost::iterator_facade,并遇到了这段代码:

    friend class boost::iterator_core_access;
    template <class> friend class Iterator;

第二行是什么意思?我对朋友课很熟悉,但我想我以前没有见过template <class>在任何东西前面。


上下文:

template <class Value>
class node_iter
  : public boost::iterator_facade<
        node_iter<Value>
      , Value
      , boost::forward_traversal_tag
    >
{
 public:
    node_iter()
      : m_node(0) {}
    explicit node_iter(Value* p)
      : m_node(p) {}
    template <class OtherValue>
    node_iter(node_iter<OtherValue> const& other)
      : m_node(other.m_node) {}
 private:
    friend class boost::iterator_core_access;
    template <class> friend class node_iter;
    template <class OtherValue>
    bool equal(node_iter<OtherValue> const& other) const
    {
        return this->m_node == other.m_node;
    }
    void increment()
    { m_node = m_node->next(); }
    Value& dereference() const
    { return *m_node; }
    Value* m_node;
};
typedef impl::node_iterator<node_base> node_iterator;
typedef impl::node_iterator<node_base const> node_const_iterator;

这意味着Iterator是一个模板类,只有一个模板参数。Iterator的所有实例都被授予友谊。

Iterator<int>是班上的朋友。

Iterator<bool>是班上的好朋友。

Iterator<MyClass>是班上的好朋友。

你懂的。

假设你有一个类模板Foo

template <typename T> class Foo
{
   public:
      Foo() : data(0) {}
   prvavte:
      T data;
};

当您使用

实例化类模板时:
Foo<int> a;
Foo<float> b;

在编译时创建两个类。Foo<int>不能访问Foo<float>的私有区,反之亦然。这有时很不方便。

你不能这样做:

b = a;  // If you wanted to pull the data from a and put it in b.

即使在类中添加了赋值操作符,

template <typename T> class Foo
{
   public:
      Foo() : data(0) {}
      template <typename T2> Foo& operator=(Foo<T2> const& rhs)
      {
         this->data = rhs.data;
         return *this;
      }
   private:
      T data;
};

它不会工作,因为Foo<T>没有访问Foo<T2>的私有部分。要解决这个问题,你可以使用友元声明。

template <typename T> class Foo
{
   public:
      template <class> friend class Foo;
      Foo() : data(0) {}
      template <typename T2> Foo& operator=(Foo<T2> const& rhs)
      {
         this->data = rhs.data;
         return *this;
      }
   private:
      T data;
};

现在,你可以使用:

Foo<int> a;
Foo<float> b;
b = a;

明确实例化:http://www.cplusplus.com/articles/1C75fSEw/

它允许你实例化模板而不实际使用它。