【问题标题】:C++: friend template class / template non-type parameterC++:朋友模板类/模板非类型参数
【发布时间】:2014-10-03 23:21:59
【问题描述】:

我想实现通用图形类,但我仍然遇到问题,缩小到以下代码:

template <class T> class B
{
    template <T> friend class A;
};


template <class T> class A
{
private:
    std::vector<B<T> *> myBs;
};


class C { };

除非我这样做,否则编译得很好:

B<C> myB;

...导致以下错误:

B.h: In instantiation of ‘class B<C>’:
In file included from A.h:12:0,
             from main.cpp:16:
main.cpp:30:10:   required from here
B.h:15:1: error: ‘class C’ is not a valid type for a template non-type parameter
{
^
B.h:11:11: error: template parameter ‘class T’
template <class T> class A;
          ^
B.h:16:31: error: redeclared here as ‘<declaration error>’
template <T> friend class A;

我的想法是绝对错误的吗,我是否遗漏了什么,或者这样的结构是不可能的、混乱的、奇怪的或非常(...)非常糟糕的事情?

【问题讨论】:

    标签: c++ class templates friend non-type


    【解决方案1】:

    问题在于您的friend 声明。我建议你先声明A 类,然后使用更简单的friend 声明。喜欢

    template<class T> class A;
    
    template<class T>
    class B
    {
        friend A<T>;
        ...
    };
    

    【讨论】:

      【解决方案2】:

      问题是您是否只想让A&lt;T&gt; 成为B&lt;T&gt; 的朋友。 然后使用 Joachim 的解决方案!

      如果你想让任何 A 成为朋友,那么你需要这样做:

      template <class T> class B
      {
          template<class> friend class A;
      };
      

      【讨论】:

      • 好主意,但目前我只想让 A 成为 B 的朋友
      猜你喜欢
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      相关资源
      最近更新 更多