“template <class> friend class Foo” 是什么意思?

6

我正在探索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;

1
http://en.cppreference.com/w/cpp/language/friend - chris
这里的class node_iter是自己的朋友。看起来这行可能是多余的,因为类默认情况下就是自己的朋友。 - user142650
2个回答

5
这只是意味着Iterator是一个具有一个模板参数的模板类。友元关系适用于所有实例化的IteratorIterator<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;

啊,我想我错过的部分基本上是template <class>包含一个未命名的模板参数。我猜那很少发生。 - vmrob

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接