Search code examples
c++templatesfriend

Template functions as friends of template classes


If I have a template class, e.g. template <typename T> class Foo, I know that it is possible to declare template functions as friends of this class using the same template parameters. See the following code:

#include <iostream>

template <typename T> class Foo;

template <typename U>
U bar(Foo<U>& f)
{
  return f.val_;
}

template <typename T>
class Foo {
private:
  T val_, imag;

public:
  Foo(T val) : val_(val) {}

  friend T bar<>(Foo<T>& f);
};


int main()
{
  Foo<int> foo(1);
  std::cout << bar(foo) << std::endl;
}

But how is it possible to declare a template function with more template parameters to be a friend of a template class using the template parameters of the template class and only the remaining template parameters are variable?

In detail I want something like this:

template <typename T> class Foo;

template <typename U, typename V>
U bar(Foo<U>& f, V& v)
{
    ...
}

template <typename T>
class Foo {
private:
  T val_, imag;

public:
  Foo(T val) : val_(val) {}

  template<typename V> friend T bar<>(Foo<T>& f, V& v);
};

I would be pleased if somebody could help me with this problem.


Solution

  • In short, you can't do that, even tough it seems a logical choice. Here is why:

    If you declare a friend like this: template<typename V> friend T bar<>(Foo<T>& f, V& v); you actually refer to another function , not the one with two template arguments. If you have for example the type Foo<int> then your the declaration of friend refferts to the function which has this definition:

    template < typename V>
    int bar(Foo<int>& f, V& v);
    

    which is a totally different function then:

    template <typename U, typename V>
    U bar(Foo<U>& f, V& v);