与模板返回函数的返回错误

Compile error with template return type for a function

本文关键字:返回 错误 函数      更新时间:2023-10-16

我在.hpp中具有此声明的模板类:

  template<class FriendClass> class SocialConnection{
    typedef std::set<FriendClass> FriendSet;
    FriendSet _socialFriends;
    public:
       virtual const FriendSet& getFriends();

和.cpp:

const SocialConnection::FriendSet& SocialConnection::getFriends() {
    return _socialFriends;
}

编译器给我一个集合声明的错误: Expected a class or namespace为行const SocialConnection::FriendSet& SocialConnection::getFriends()

我一直在搜索为什么两个小时,没有任何结果。我无法在实现中使用模板类的名称?我该怎么做?我丢失了什么语法?

  1. 您的getfriends定义中的班级名称缺少模板参数。
  2. 您无法真正将模板代码放在CPP文件中,并期望它编译。它是一个模板,因此在使用何处将其实例化为一种类型。因此,您需要将其放在标题中。

    模板&lt;typename f>

    const typename socialconnection&lt;f> :: Friendset&amp;社会共同&lt;f> :: getfriends(){ 返回_社交朋友;}

正确的定义很长:

template<typename FriendClass>
const typename SocialConnection<FriendClass>::FriendSet&
SocialConnection<FriendClass>::getFriends()
{
    return _socialFriends;
}

@pwned所说的话;在实例化时需要可见,因此将其放入标题中。请参阅此问题以进行解释。

还要注意返回类型之前的typename - 它是必要的,因为FriendSet依赖的名称。此问题深入解释。