`template <class>朋友类Foo`是什么意思?</class>

时间:2014-06-06 01:17:58

标签: c++ boost friend

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

2 个答案:

答案 0 :(得分:5)

这只是意味着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;

答案 1 :(得分:0)

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

它允许您在不实际使用模板的情况下实例化模板。