Vin*_*ent 5 c++ gcc templates ostream
我有一个问题是重载<<流操作符,我找不到解决方案:
template<class T, unsigned int TN>
class NVector
{
inline friend std::ostream& operator<< (
std::ostream &lhs, const NVector<T, TN> &rhs);
};
template<class T, unsigned int TN>
inline std::ostream& NVector<T, TN>::operator<<(
std::ostream &lhs, const NVector<T, TN> &rhs)
{
/* SOMETHING */
return lhs;
};
Run Code Online (Sandbox Code Playgroud)
它会产生以下错误消息:
警告:朋友声明'std :: ostream&operator <<(std :: ostream&,const NVector&)'声明一个非模板函数[-Wnon-template-friend]
错误:'std :: ostream&NVector :: operator <<(std :: ostream&,const NVector&)'必须只有一个参数
如何解决这个问题?
非常感谢你.
Dav*_*eas 12
您的代码中存在两个不同的问题,第一个是friend声明(如警告清楚地说明,可能不太清楚)可以将单个非模板化函数声明为朋友.也就是说,当您实例化模板时,NVector<int,5>它会将非模板化函数声明std::ostream& operator<<(std::ostream&,NVector<int,5>)为朋友.请注意,这与声明您作为好友提供的模板功能不同.
我建议你在类定义中定义friend函数.您可以在此答案中阅读更多相关内容.
template <typename T, unsigned int TN>
class NVector {
friend std::ostream& operator<<( std::ostream& o, NVector const & v ) {
// code goes here
return o;
}
};
Run Code Online (Sandbox Code Playgroud)
或者,您可以选择其他选项:
operator<<模板声明为朋友(将授予对模板的任何和所有实例化的访问权限),print( std::ostream& )成员函数并从模板化的非朋友调用它operator<<.我仍然会选择与非模板函数建立联系,并在模板化类中提供定义.第二个问题是,当你想在左侧参数的类之外定义一个运算符时,运算符是一个自由函数(没有绑定到一个类),因此它不应该被限定:
template<class T, unsigned int TN>
inline std::ostream& operator<<(std::ostream &lhs, const NVector<T, TN> &rhs)
{
/* SOMETHING */
return lhs;
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7809 次 |
| 最近记录: |