【问题标题】:What is the right way to write friend function declarations in template class?在模板类中编写友元函数声明的正确方法是什么?
【发布时间】:2017-09-27 12:08:25
【问题描述】:

我正在尝试编写自己的向量模板类,但是在编写友元函数声明时遇到了一些问题。

一开始我是这样写的:

template <typename T, typename Alloc = std::allocator<T>>
class vector {
public:
    friend bool operator==(const vector<T, Alloc>&, const vector<T, Alloc>&);
};

但是编译器报告了我声明了一个非模板函数的警告。所以我把朋友声明改成这样:

template <typename T, typename Alloc = std::allocator<T>>
class vector {
public:
    template <typename E, typename F>
    friend bool operator==(const vector<E, F>&, const vector<E, F>&);
};

到目前为止一切都很好,但我认为仍然存在问题。如果我这样写,我会创建所有operator== 函数,它们将两个模板参数作为它的友元函数。例如,operator==(const vector&lt;int&gt;&amp;, const vector&lt;int&gt;&amp;) 和 operator==(const vector&lt;double&gt;&amp;, const vector&lt;double&gt;&amp;) 都是 vector&lt;int&gt; 的好友函数。

在模板类中编写友元函数的正确方法是什么?

【问题讨论】:

    标签: c++ templates vector friend


    【解决方案1】:

    好友非模板函数

    但是编译器报告了一个警告,我声明了一个非模板函数。

    是的,您在类定义中声明了一个非模板函数。这意味着如果您在类定义之外定义它,则必须将其定义为非模板函数,并且对于所有可能的实例化,例如:

    bool operator==(const vector<int>& v1, const vector<int>& v2)
    {
        ...
    }
    bool operator==(const vector<char>& v1, const vector<char>& v2)
    {
        ...
    }
    

    这很难看,你可以在类定义中定义它

    template <typename T, typename Alloc = std::allocator<T>>
    class vector {
    public:
        friend bool operator==(const vector<T, Alloc>&, const vector<T, Alloc>&) {
            ...
        }
    };
    

    好友功能模板

    如果你想将其定义为模板函数,并限制友谊范围,你可以

    // forward declaration
    template <typename T, typename Alloc>
    class vector;
    
    // forward declaration
    template <typename T, typename Alloc>
    bool operator==(const vector<T, Alloc>& v1, const vector<T, Alloc>& v2);
    
    template <typename T, typename Alloc = std::allocator<T>>
    class vector {
    private:
        int i;
    public:
        // only the instantiation of operator== with template parameter type of current T and Alloc becomes friend
        friend bool operator==<>(const vector<T, Alloc>& v1, const vector<T, Alloc>& v2);
    };
    
    template <typename T, typename Alloc = std::allocator<T>>
    bool operator==(const vector<T, Alloc>& v1, const vector<T, Alloc>& v2)
    {
        ...
    }
    

    那么,对于vector&lt;int&gt;,只有bool operator==(const vector&lt;int&gt;&amp;, const vector&lt;int&gt;&amp;) 是友元,其他实例如bool operator==(const vector&lt;double&gt;&amp;, const vector&lt;double&gt;&amp;) 不是。

    LIVE

    【讨论】:

      猜你喜欢
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多