user2052436
user2052436

Reputation: 4765

Friend template function of a template class

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 );

Upvotes: 2

Views: 641

Answers (1)

slaphappy
slaphappy

Reputation: 6999

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 );
};

Upvotes: 2

Related Questions