Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I befriend a template parameter?

When researching an answer to a question (based on this answer) I tried to do the following:

template <class T>
class friendly {
    friend class T;
};

friendly<string> howdy;

This fails to compile with the following error:

error: template parameter "T" may not be used in an elaborated type specifier friend class T;

From what I can understand from my good friend Google this is so that I won't accidentally try to instantiate friendly<int> but why should this be an error when compiling the template? Should't it be an error when instantiating the template with an invalid type (such as had I written int f() { return T::foo(); })

like image 401
Motti Avatar asked Jun 17 '09 13:06

Motti


2 Answers

Section 7.1.5.3 of the standard explicitly describes this as an example of an illformed elaborated type specifier.

A discussion about the subject can be found here.

like image 105
Dave Van den Eynde Avatar answered Sep 20 '22 07:09

Dave Van den Eynde


A bit more googleling brought up Extended friend Declarations (PDF) for C++0x.

This document contains the following:

template <typename T> class R {
    friend T;
};
R<C> rc; // class C is a friend of R<C>
R<int> ri; // OK: “friend int;” is ignored

Which goes even further than what I thought (ignoring illegal friend decelerations rather than failing during instantiation). So I guess the answer is that there isn't a good reason and it's being rectified.

like image 30
Motti Avatar answered Sep 22 '22 07:09

Motti