Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to mark an alias template as a friend?

Imagine we have this code:

template <class, class>
class Element
{};

template <class T>
class Util
{
public:
   template <class U>
   using BeFriend = Element<T, U>;
};

Is it possible to mark BeFriend as a friend ? (Of Util, or any other class).

 Edit

The "obvious" syntax were tried, but both failed with Clang 3.6.

template <class> friend class BeFriend;
template <class> friend BeFriend;

I did not know about the second syntax, but found it in this answer. It seems to work (and be required) for non-template aliases, but does not help in this case where the alias is templated.

(Note: as some could infer from the minimal example, I am looking for a way to work-around the limitation that C++ does not allow to friend a partial template specialization)

like image 869
Ad N Avatar asked Nov 06 '15 09:11

Ad N


People also ask

Can we declare a template function as the friend of the class?

Template friendsBoth function template and class template declarations may appear with the friend specifier in any non-local class or class template (although only function templates may be defined within the class or class template that is granting friendship).

How do I declare a friend template class in C++?

class B{ template<class V> friend int j(); } template<class S> g(); template<class T> class A { friend int e(); friend int f(T); friend int g<T>(); template<class U> friend int h(); }; Function e() has a one-to-many relationship with class A . Function e() is a friend to all instantiations of class A .

Where to put friend class declaration?

and ->) unless they're members of another class. A friend function is declared by the class that is granting access. The friend declaration can be placed anywhere in the class declaration. It isn't affected by the access control keywords.

What is an alias name type?

An alias can be any name used in place of a birth name. While there may be legitimate reasons for using another name, this is often used by criminals, as they don't wish to have their true identity revealed, or they have a short nickname they go by instead of their birth name.


1 Answers

I think you can't do that because partial specializations could not be declared as friend.

From the stardard, [temp.friend]/7

Friend declarations shall not declare partial specializations. [ Example:

template<class T> class A { };
class X {
  template<class T> friend class A<T*>; // error
};

—end example ]

You have to specify a more generic version such as:

template <class, class> friend class Element;

or a full specified version, such as:

using BeFriend = Element<T, int>;
friend BeFriend;
like image 107
songyuanyao Avatar answered Oct 04 '22 12:10

songyuanyao