Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using friend in templates

Tags:

c++

gcc

templates

I am writing a small class, the class is basically a factory for the C class, but I want other classes to be able to access some of the methods.

template<class C>
class CFactory {
public:   
   friend class C;
};

This should make the fields of CFactory available to the class C, but the compiler thinks otherwise.

I'm getting the following two errors using gcc on a mac.

error: using template type parameter 'C' after 'class'

error: friend declaration does not name a class or function

Can anyone tell me what I'm doing wrong and how to get et right?

like image 297
Martin Kristiansen Avatar asked Jun 12 '11 09:06

Martin Kristiansen


2 Answers

Unfortunately, in my understanding, this isn't allowed in current standard.
§7.1.5.3/2 says:

[Note: ... within a class template with a template type-parameter T, the declaration
friend class T;
is ill-formed. -end note]

On a related note, this restriction seems to be removed in C++0x (§11.3/3 in N3290).
Incidentally, MSVC may allow this if we write simply friend T;.

like image 106
Ise Wisteria Avatar answered Sep 27 '22 21:09

Ise Wisteria


Ise's response is correct -- Comeau's FAQ contains a question concerning this issue in more detail.

However, perhaps you can try an extra template indirection that might work? Something like this:

template <typename T>
struct FriendMaker
{
    typedef T Type;
};

template <typename T>
class CFactory
{
public:
    friend class FriendMaker<T>::Type;
};

This seems to only work with gcc 4.5.x however so I wouldn't rely on it.

like image 35
greatwolf Avatar answered Sep 27 '22 21:09

greatwolf