Feb 26, 2014

[C++11] Extended friend declarationen

How come forward declaration is not needed for friend class concept?
extended friend declaration elaborated-type-specifier :
template <class T> class A {
friend class T; // Error in C++98, using template type-parameter 'T' after 'class' <=elaborated-type-specifier
};
simple-type-specifier :
template <class T> class A {
friend T; // OK in C++11 <= simple-type-specifier
};
class A;
class B;

class X {
friend class A; //OK in both C++98 and C++11
friend B; //Error in C++98 for missing the class-key; OK in C++11
};
Base type case also be friend:
class C;
template <typename T> class A {
friend T;
};

A<C> rc;
A<int> Ri; // <= Base type case also be friend
This feature also introduces a new name lookup rule for friend declarations. If a friend class declaration does not use an elaborated-type-specifier, then the compiler also looks for the entity name in scopes outside the innermost namespace that encloses the friend declaration. Consider the following example:
struct T { };

namespace N {
struct S {
friend T; // OK in C++11
};
}
In this example, if this feature is in effect, the friend declaration statement does not declare a new entity T, but looks for T in the scope outside namespace N. If no T is found, the compiler issues an error.
class X {
friend D; // Error in C++98 for missing the class-key. Also Error in C++11 for lookup failure! D _must_ be pre-declared!
friend class D; // OK in both C++98 and C++11; Declares a new entity class D.
};
class Derived;
typedef Derived D;

class Sibling;
typedef Sibling S;

class Base{
public:
friend D; //Error in C++98; OK in C++11
friend class S; //Error in both C++98 and C++11 <=Cannot use an elaborated-type-specifier in the friend declaration!!
};
template <typename T>
class Node;

template <typename T>
class Tree
{
//class Node template must be declared first(externed). 
//Unlike usual class, friend an undeclared class is simply declaring it(extern).
  friend class Node<T>; 
};

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.