【问题标题】:c++ declaring stl vector using type of befriending class as template argumentc++ 使用友好类的类型作为模板参数声明 stl 向量
【发布时间】:2012-10-15 02:02:35
【问题描述】:

我有以下代码:

template <typename T>
class A {
    friend class B;
    struct model_struct {
       [...]
    }
}

template <typename T>
class B {
    func {
        typename vector<A<T>::model_struct > myVec;
    }
}

向量声明给了我以下编译错误:

错误:“模板类 std::vector”的模板参数列表中参数 1 的类型/值不匹配

错误:期望一个类型,得到'ObjectExtraction::model_struct'

有什么想法吗?

【问题讨论】:

  • func 应该是什么?
  • 你试过把 typename 放在A&lt;T&gt;::model_struct 之前吗?

标签: c++ templates


【解决方案1】:

似乎缺少三件事:

  • 类定义末尾的分号
  • 朋友声明中的模板参数
  • vector 声明中的 typename 说明符

后者是导致错误的问题。

我不确定B 定义中的func {...} 是做什么的;您可能需要考虑将其删除。

最后,您需要B 模板的前向声明,因此您可以将它实际用于A 中的朋友声明。

以下是更正代码的尝试:

template <typename T>
class B; // Forward-declaration

template <typename T>
class A {
    friend class B<T>;  // template argument added
    struct model_struct {
       /*...*/
    };  // added semicolon
}; // semicolon added

template <typename T>
class B {
   /* Removed 'func'. */
   typename vector<typename A<T>::model_struct > myVec; // 'typename' added
};

【讨论】:

  • 所以将类型名放入向量声明中修复了它。我还需要在向量之前输入类型名吗?
  • @Mustafa 不,你可以删除那个。
  • 非常感谢,我确实需要前向声明来修复出现的另一个错误。
【解决方案2】:

你应该这样修改:

template <typename T>
class A {
    friend class B;
    struct model_struct {
       [...]
    }
}

template <typename T>
class B {
    func {
        vector<typename A<T>::model_struct > myVec;
    }
}

【讨论】:

  • 由于friend 声明中缺少模板参数和缺少分号(除了问题的cmets 中提到的func 问题),这将无法编译。
猜你喜欢
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2014-10-03
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 1970-01-01
相关资源
最近更新 更多