Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template parameter as a friend

In C++03 the following is illegal, although some compilers support it.

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

Has this been legalized in C++11? (Sorry, didn't have time to read the draft myself, just hoping someone knows this)

like image 695
Armen Tsirunyan Avatar asked Jun 28 '11 16:06

Armen Tsirunyan


People also ask

Can template function friends?

One-to-one: A template function instantiated with one set of template arguments may be a friend to one template class instantiated with the same set of template arguments. This is also the relationship between a regular non-template class and a regular non-template friend function.

What do you mean by template parameters?

In UML models, template parameters are formal parameters that once bound to actual values, called template arguments, make templates usable model elements. You can use template parameters to create general definitions of particular types of template.

What is the role of parameter in a template?

Similar to how standard function parameters may be used to send values to a function, template parameters allow you to pass types to a function as well. A template parameter is a specific form of the parameter that can be used to pass a type as an argument.

What are non-type parameters for templates?

A template non-type parameter is a template parameter where the type of the parameter is predefined and is substituted for a constexpr value passed in as an argument. A non-type parameter can be any of the following types: An integral type. An enumeration type.


2 Answers

From section §11.3, 3 in N3291:

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

So it is legal in C++11.

like image 162
Praetorian Avatar answered Sep 22 '22 06:09

Praetorian


Yes c++0x allows template parameter to be friends.

Well, I happened to remember read it in the draft before but could not find the reference..anyways @Praetorian's answer nailed it.

like image 28
Alok Save Avatar answered Sep 22 '22 06:09

Alok Save