gpt4 book ai didi

c++ - 如何告诉编译器我的 friend 函数是函数模板

转载 作者:行者123 更新时间:2023-11-30 02:32:05 25 4
gpt4 key购买 nike

这是我的代码:

#include <iostream>
#include <cstddef>

class alloc
{

};

template <class T, class Alloc = alloc, size_t BufSiz = 0>
class deque
{
public:
deque() { std::cout << "deque" << std::endl; }
};

template <class T, class Sequence = deque<T> >
class stack
{
public:
stack() { std::cout << "stack" << std::endl; }
private:
Sequence c;
friend bool operator== <> (const stack<T, Sequence>&, const stack<T, Sequence> &);
friend bool operator< <> (const stack<T, Sequence>&, const stack<T, Sequence>&);
};

template <class T, class Sequence>
bool operator== (const stack<T, Sequence>&x, const stack<T, Sequence>&y)
{
return std::cout << "opertor == " << std::endl;
}

template <class T, class Sequence>
bool operator < (const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
return std::cout << "operator <" << std::endl;
}

int main()
{
stack<int> x; // deque stack
stack<int> y; // deque stack

std::cout << (x == y) << std::endl; // operator == 1
std::cout << (x < y) << std::endl; // operator < 1
}

我只是想一个简单的 <> 符号告诉编译器我的函数是函数模板。但是我得到两行错误: friend 只能是类或函数

friend bool operator== <> (const stack<T, Sequence>&, const stack<T, Sequence> &);
friend bool operator< <> (const stack<T, Sequence>&, const stack<T, Sequence>&);

我该如何解决。

最佳答案

只需使用以下语法:

template<typename T1, typename Sequence1>
friend bool operator== (const stack<T1, Sequence1>&, const stack<T1, Sequence> &);

template<typename T1, typename Sequence1>
friend bool operator< (const stack<T1, Sequence1>&, const stack<T1, Sequence>&);

您需要第一个模板参数与 T 不同,第二个模板参数与 Sequence 不同,否则您将隐藏类的模板参数。

关于c++ - 如何告诉编译器我的 friend 函数是函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36820985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com