Jpellat
Jpellat

Reputation: 917

Compile error with template return type for a function

I have a template class with this declaration in the .hpp:

  template<class FriendClass> class SocialConnection{

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

And in the .cpp:

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

The compiler gives me an error for the set declaration: Expected a class or namespace for the line const SocialConnection::FriendSet& SocialConnection::getFriends()

I have been searching why for two hours and without any result. I can't use the name of my template class in the implementation? How I can do that? Anything of syntax that I have lost?

Upvotes: 2

Views: 318

Answers (2)

nurettin
nurettin

Reputation: 11736

  1. The class name in your getFriends definition is missing the template argument.
  2. You can't really put your template code in a cpp file and expect it to compile. It is a template, so it is instantiated as a type wherever it is used. Therefore you will need to put it in a header.

    template < typename F>

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

Upvotes: 5

jrok
jrok

Reputation: 55395

The correct definition is rather long-winded:

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

And what @pwned said; it needs to be visible at the point of instantiation, so put it in the header. See this question for an explanation.

Note also typename before the return type - it's neccessary, because FriendSet is a dependent name. This question explains it in-depth.

Upvotes: 2

Related Questions