运算符的模板类中的友元函数<<
Friend function in a template class for operator<<
在.cpp文件中声明模板类的友元函数(对于std::ostream&operator<<)的正确方法是什么?
我目前的实现不起作用:
// MyTest.h
template<class T, unsigned int TSIZE> class MyTest
{
inline friend std::ostream& operator<< <T, TSIZE> (std::ostream &lhs, const MyTest<T, TSIZE> &rhs);
};
// MyTest.cpp
template<class T, unsigned int TSIZE> inline friend std::ostream& operator<< <T, TSIZE> (std::ostream &lhs, const MyTest<T, TSIZE> &rhs)
{
// IMPLEMENTATION
}
要像您所做的那样引用operator<< <T, TSIZE>
,这是一个模板专用化,主模板的声明必须可见。operator<<
需要MyTest
的声明,因为它作为参数出现。
// Declare MyTest because operator<< needs it
template<class T, unsigned int TSIZE> class MyTest;
// Declare primary template
template<class T, unsigned int TSIZE>
inline std::ostream& operator<<(std::ostream& lhs, const MyText<T, TSIZE>& rhs);
template<class T, unsigned int TSIZE> class MyTest
{
// Specialization MyTest<T, TSIZE> only declares
// specialization operator<< <T, TSIZE> as friend
// Note that you can just use '<>' to designate the specialization,
// template parameters are deduced from the argument list in this case
inline friend std::ostream& operator<< <> (std::ostream &lhs, const MyTest<T, TSIZE> &rhs);
};
您的定义应该与这些声明相匹配。注意,由于operator<<
是一个模板,它的定义很可能在标题中。
在编写所有这些抢先声明时,另一种需要较少工作的选择是MyTest<T, TSIZE>
将整个模板声明为友元,而不仅仅是使用MyTest<T, TSIZE>
的专用化。
// in MyTest definition
template<typename U, unsigned USIZE>
inline friend std::ostream& operator<<(std::ostream& lhs, const MyTest<U, USIZE>& rhs);
您的定义也应该与这样的声明相匹配(模板参数的名称与匹配的声明和定义无关)。
为了完整起见,我将提到,当涉及到类模板的朋友时,另一种选择是在类模板定义中定义它。这定义了一个非模板朋友函数,该函数对于每个专业化都是唯一的。
// in MyTest definition
friend std::ostream& operator<<(std::ostream& lhs, MyTest const& rhs)
{ /* implementation */ }
不可能引用这样的函数(例如,与其他选项不同,&ns::operator<<
不起作用),它们只能通过ADL找到。
还不完全清楚最初的帖子想要什么。我认为它想要以下内容:
// Some template class.
template<class T, unsigned int TSIZE> class MyTest { };
// Some template function.
template<class T, unsigned int TSIZE> std::ostream& operator<< (std::ostream &lhs, const MyTest<T, TSIZE> &rhs)
{
// IMPLEMENTATION
}
现在有必要将此模板函数声明为类的友元,因为此函数需要访问My test
的受保护对象。这可以通过以下定义来实现:
template<class T, unsigned int TSIZE> class MyTest
{
template<class T1, unsigned int TSIZE1>
friend std::ostream& operator<< (std::ostream &lhs, const MyTest<T1, TSIZE1> &rhs);
};
friend
声明前面需要模板头,因为这是一个不相关的模板函数,不属于当前模板类。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 内置函数可查看CPP中的成员变量
- 为什么COUT在朋友函数中不起作用,该功能超载了操作员&lt;&lt;这是一个iStream运算符
- 重载运算符<<:此运算符函数的参数太多
- std::pair的默认构造函数<>将基本类型(int等)设置为零