Martin Kristiansen
Martin Kristiansen

Reputation: 10222

Using friend in 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?

Upvotes: 12

Views: 1853

Answers (3)

greatwolf
greatwolf

Reputation: 20858

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.

Upvotes: 5

Ise Wisteria
Ise Wisteria

Reputation: 11669

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;.

Upvotes: 12

Kiril Kirov
Kiril Kirov

Reputation: 38173

C can be anything - int, double, etc. and they are not classes. In general, this class C is not class. And you cannot have something like:

class A
{
    friend class int;
    //..
};

One more reason to prefer typename, instead of class when using templates

Upvotes: 3

Related Questions