【问题标题】:What does `template <class> friend class Foo` mean?`template <class>friend class Foo` 是什么意思?
【发布时间】:2014-06-06 01:17:58
【问题描述】:

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

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

第二行是什么意思?我对朋友班很熟悉,但我想我以前没有在任何东西前面看到过template &lt;class&gt;


这是上下文:

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;

【问题讨论】:

标签: c++ boost friend


【解决方案1】:

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

Iterator&lt;int&gt; 是班级的朋友。

Iterator&lt;bool&gt; 是班上的朋友。

...

Iterator&lt;MyClass&gt; 是班级的朋友。

你明白了。

示例用法

假设你有一个班级模板Foo

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

当您使用以下方法实例化类模板时:

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

您在编译时创建了两个类。 Foo&lt;int&gt; 无权访问 Foo&lt;float&gt; 的私有部分,反之亦然。这有时会带来不便。

你不能这样做:

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&lt;T&gt; 无权访问Foo&lt;T2&gt; 的私有部分。要解决这个问题,您可以使用朋友声明。

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 &lt;class&gt; 包含一个未命名的模板参数。我想这很少出现。
【解决方案2】:

显式实例化:http://www.cplusplus.com/articles/1C75fSEw/

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 2019-06-16
    • 2021-12-19
    • 1970-01-01
    • 2014-12-03
    相关资源
    最近更新 更多