Aarkan
Aarkan

Reputation: 4109

Declare a template function as friend

I have a global function like this:

namespace X
{
namespace Y
{
template <R, ...T>
R foo(T&&... args)
{
    R r(args...);
    return r;
}
}
}

Then in another class A, I want to declare this function foo as friend of A. So I did:

class A
{
template <R, ...T>
friend R X::Y::foo(T&&... args);
A(int x, int y){}
};

Now when, I call X::Y::foo<A>(4, 5) it fails to compile with error that foo can not access the private constructor of A. I am unable to understand the error, how do I declare the foo as friend of A correctly?

Thanks in advance.

Upvotes: 1

Views: 139

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126432

After fixing the syntactic issues with template parameters and parameter packs, this seems to work:

namespace X
{
    namespace Y
    {
        template <typename R, typename ...T>
        R foo(T&&... args)
        {
            R r(args...);
            return r;
        }
    }
}

class A
{
    template <typename R, typename ...T>
    friend R X::Y::foo(T&&... args);
    A(int x, int y){}
};

int main()
{
    X::Y::foo<A>(1, 2);
}

Here is a live example of the above code compiling.

Upvotes: 2

Related Questions