c++ - 模板类和 Friend 模板函数

标签 c++ templates

C++ 入门:模板和函数

template <typename>
class BlobPtr;

template <typename>
class Blob;

template <typename T>
bool operator==(const Blob<T>&, const Blob<T>&);
template <typename T>
class Blob
{
    friend class BlobPtr<T>;
    friend bool operator==<T>(const Blob<T>&, const Blob<T>&);
};

然后:

Blob<char> ca;
Blob<int> ia;

The members of BlobPtr<char> may access the nonpublic parts of ca (or any other Blob object), but ca has no special access to ia (or any other Blob) or to any other instantiation of Blob.

问题: 我想测试代码。如何使用 ca 访问 ia 的非公开部分?澄清一下,我知道这是不可能的,但我想测试代码以查看错误。

最佳答案

您可以只添加 template使用前 friend .

template<typename T>
class Blob
{
    template<typename T1>
    friend class Blob;

public:
    template<typename T1>
    bool operator==(const Blob<T1>& other)
    {
        return i == other.i;
    }
private:
    T i;
};

Blob<int> i;
Blob<char> j;

int main()
{
    i == j;
}

添加模板使得每个Blob<T>类(class)变成了彼此的 friend 类(class)。所以,Blob<int> 的每个成员函数可以访问 Blob<char> 的私有(private)成员反之亦然。

关于c++ - 模板类和 Friend 模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51255357/

相关文章:

c++ - Boost::Asio::Ip::Tcp::Iostream 问题

python - 使用 pybind11,如何将我的代码拆分为多个模块/文件?

c++ - ISO 8601 时间戳 C++

templates - html/template if 范围索引子句

templates - 是否可以在 Julia 中声明对任何结构的一般引用?

c++ - 使用 cmake 和 mingw 在 mac OSX 上交叉编译 dll

c++ - 具有嵌套结构/类的 POD 性

delphi - 如何减少新表单的 "uses"样板?

javascript - JavaScript 模板引擎的现状?

c++ - 原子比较、多处理器、C/C++ (Linux)