如何使模板成为T的朋友? [英] How to make a template a friend of T?

查看:109
本文介绍了如何使模板成为T的朋友?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个C类和一个容器模板T_CONTAINER.
我有一个日期函数,只想向T_CONTAINER公开.
我怎样才能做到这一点?请注意,我使用Visual C ++ 2010作为编译器.

我不得不公开这些功能,这是不理想的.

我尝试过:

Let''s say I have a class C and a container template T_CONTAINER.
I have a function in date that I only want to expose to T_CONTAINER.
How can I do this? Note that I am using Visual C++ 2010 as a compiler.

I''ve had to make the functions public, which is less than desirable.

I''ve tried:

class C;
#include "T_CONTAINER.H"
class C {
     friend T_CONTAINER< C >;
}

推荐答案

尝试了以下可行的方法.
Tried the following which works.
template <typename T>
class A
{
    T *_t;
public:
    A(T *t) : _t(t) {}
    void accessT()
    {
        _t->privateAccess();
    }
};
class C {
    void privateAccess()
    {
        cout << "private" << endl;
    }
    friend A<C>;
};
int main()
{
    C c;
    A<C> a(&c);
    a.accessT();
    return 0;
}


使用friend声明,模板类可以访问类C的私有方法.我不知道您在哪里出错.

大多数容器类都有一些用于分配器等的默认模板参数.确保它们在您的朋友声明中匹配.


With the friend declaration, the template class can access the private methods of class C. I don''t know where you went wrong.

Most container classes have some default template arguments for allocators and such. Make sure they match in your friend declaration.


这篇关于如何使模板成为T的朋友?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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