加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 模板类的朋友模板功能

发布时间:2020-12-16 07:29:29 所属栏目:百科 来源:网络整理
导读:我有以下简化代码: template class Tclass A{public: template class U static U foo(T* p) { p; return U(); }};class B{ /*template class T template class U friend U AT::fooU(T*);*/ friend B AB::fooB(B*); B() {}public:};...AB::fooB(nullptr); 而
我有以下简化代码:

template <class T>
class A
{
public:
    template <class U>
    static U foo(T* p)
    {
        p;
        return U();
    }
};

class B
{
    /*template <class T>
    template <class U>
    friend U A<T>::foo<U>(T*);*/
    friend B A<B>::foo<B>(B*);
    B()
    {}
public:
};
...
A<B>::foo<B>(nullptr);

而且效果很好.但是我没有做过的事情被评论:

/*template <class T>
template <class U>
friend U A<T>::foo<U>(T*);*/

我不知道我应该使用什么语法来使它工作.所以我需要将我的朋友声明推广到所有可能的类型.我已经尝试了很多语法变体但没有成功.有人可以指出我应该写什么而不是我的注释代码才能使它有效?
谢谢!

解决方法

你在寻找什么

template <class T>
template <class U>
friend U A<T>::foo(T*);

以下适用于IdeOne.com

#include <iostream>

template <class T>
class A
{
public:
  template <class U>
  static U foo(T* p)
  {
    p;
    return U();
  }
};

class B
{
  template <class T>
  template <class U>
  friend U A<T>::foo(T*);

  B() {}

public:
  void hello() const
  {
    std::cout << "I'm a B!" << std::endl;
  }
};

int main(int,char*[])
{
  A<B>::foo<B>(NULL).hello();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读