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

标签 c++ templates vector friend

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

一开始我是这样写的:

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<int>&, const vector<int>&)operator==(const vector<double>&, const vector<double>&)两者都是 vector<int>的友元函数。

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

最佳答案

friend 非模板函数

But the compiler reports a warning that I declare a non-template function.

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

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<int> , 只有 bool operator==(const vector<int>&, const vector<int>&)是 friend ,其他实例化如 bool operator==(const vector<double>&, const vector<double>&)不是。

LIVE

关于c++ - 在模板类中编写友元函数声明的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43696019/

相关文章:

C++获取服务网络状态linux

c++ - 处理未知大小的输入

c++ - 为什么 std::sort 不要求用户指定模板类型?

c++ - 为什么必须在哪里放置 “template”和 “typename”关键字?

C++ 集合 : how to create a map like structure

c++如何使用两个迭代器从 vector 复制范围

c++ - std::vector 在内存中是什么样的?

c++ - MySQL 从注入(inject)到参数化的麻烦转换

c++ - 为什么要使用 glTranslatef?为什么不直接更改渲染坐标?

C++ 可变参数模板类终止