Max
Max

Reputation: 15965

How can I declare a template friend function to a template class?

Sorry, this question seems to have been asked many times, but I could not get the other answers to work for my setup. I have the following class and function setup:

namespace ddd {
  template <typename T>
  class A {
    ...
  };

  template <typename T, typename U>
  A<T> a_func(const A<U> &a) {
    ...
  }
}

I want to declare a_func as a friend of A, and I want it so that a_func is a friend for all instances of A, no matter which typename is used for T and U (e,g, a_func can access A).

Thanks!

Upvotes: 0

Views: 126

Answers (1)

Seth Carnegie
Seth Carnegie

Reputation: 75130

You can do that this way (which looks like how you had it):

template<typename X>
class A {
    template<typename T, typename U>
    friend A<T> a_func(const A<U>& a);
};

template<typename T, typename U>
A<T> a_func(const A<U>& a) {
    // whatever
}

Demo

Upvotes: 1

Related Questions