c++ - 如何为嵌套在一个模板类里面的类添加友元?比如==函数。

查看:79
本文介绍了c++ - 如何为嵌套在一个模板类里面的类添加友元?比如==函数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

template <typename> class Vector;
template <typename T>
bool operator==(const typename Vector<T>::const_iterator&, const typename Vector<T>::const_iterator&); // 友元声明,签名是这么写吗?

template <typename T>
class Vector {
public:
    class const_iterator: {
        friend bool operator==(const const_iterator& lsh, const const_iteraotr& rhs);
    public:
    };
};


template <typename T>
bool operator==(const typename Vector<T>::const_iterator& lhs, const typename Vector<T>::const_iterator& rhs) { // 友元定义

}

如果直接将==友元在const_iterator里面定义,比较简单,直接写就行。但是我想在类外定义时,就不知道怎么写它的函数签名了。

解决方案

最好是这样写,你上面写的那种貌似很难实现
参考

template <typename> struct Vector;

template <typename T>
struct Vector_const_iterator;

template <typename T>
bool operator==(const Vector_const_iterator<T>& lsh, const Vector_const_iterator<T>& rhs);

template <typename T>
struct Vector {
    typedef Vector_const_iterator<T> const_iterator;
};

template <typename T>
struct Vector_const_iterator {
    friend bool operator == <> (const Vector_const_iterator<T>& lsh, const Vector_const_iterator<T>& rhs);
};


template <typename T>
bool operator==(const Vector_const_iterator<T>& lsh, const Vector_const_iterator<T>& rhs) { 
    return true;
}

这篇关于c++ - 如何为嵌套在一个模板类里面的类添加友元?比如==函数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆