2

How do I get the following code to work:

#include <array>
#include <iostream>

template<typename T>
class MyClass;

template<typename T, size_t N>
MyClass<T> myFun( const std::array<T, N>& a );

template<typename T>
class MyClass
{
    MyClass( size_t n )
    { std::cout << "Ctor with n = " << n << '\n'; }

    template<size_t N>
    friend MyClass<T> myFun<T, N>( const std::array<T, N>& a );
};


template<typename T, size_t N>
MyClass<T> myFun( const std::array<T, N>& a )
{
    return MyClass<T>( N );
}


int main()
{
    std::array<int, 3> a;
    myFun( a );
    return 0;
}

gcc does not like template<size_t N> in front of friend declaration:

error: invalid use of template-id 'myFun' in declaration of primary template friend MyClass myFun( const std::array& a );

user2052436
  • 4,321
  • 1
  • 25
  • 46

1 Answers1

2

You just need to copy the forward-declaration of the template into your friend declaration:

template<typename T>
class MyClass
{
    MyClass( size_t n )
    { std::cout << "Ctor with n = " << n << '\n'; }

    template<typename T1, size_t N>
    friend MyClass<T1> myFun( const std::array<T1, N>& a );
};
slaphappy
  • 6,894
  • 3
  • 34
  • 59
  • And also, the template parameters in the friend function decl have to have different names from the template parameters of the class. i.e. `T1` vs. `T` – ipmcc Apr 05 '14 at 17:13