I have a template class. It has a template function. Both take different template parameters. There is an internal class that needs to make a friend of the enclosing class's template function. Compiler errors abound. The following toy example shows my issue.
First, the following of course compiles (VS 2017):
template <typename T>
class Class1
{
public:
Class1() = default;
~Class1() = default;
template <typename U>
void Func(U& x) {};
};
class Class2
{
public:
Class2() = default;
~Class2() = default;
template <typename T>
template <typename U>
friend void Class1<T>::Func(U& x);
};
int main()
{
Class1<int> c1;
return 0;
}
Now let's move Class2
into Class1
with no other changes:
template <typename T>
class Class1
{
public:
Class1() = default;
~Class1() = default;
template <typename U>
void Func(U& x){};
class Class2
{
public:
Class2() = default;
~Class2() = default;
template <typename T> //Compiler error here.
template <typename U>
friend void Class1::Func(U& x);
};
};
int main()
{
Class1<int> c1;
return 0;
}
Now I get a compiler error: error C3856: 'Class1<T>::Func': class is not a class template
I've played around with various ways to declare the friend when the class is nested, but I can't get it to compile. It's possible there is no way to do what I'm trying to do.
Note that the semantics of what I'm trying to do (in the real code, not this toy example) are such that Func should be a member function. This isn't about iterators or operators, which are often, of course, non-member functions. I've seen some similar questions to mine here, but they're often related to iterators or operators and I've not yet found a question with a solution that will work for me.
Worse comes to worse, it would be okay, given my design, to declare all of Class1
a friend of Class2
(and doing so lets me work around this issue). Class2
is a tiny helper class that is completely coupled to Class1
; all of its special members, save the destructor and move ctor, are either private or deleted, and Class1::Func
is the only thing that instantiates Class2
(and returns it via move ctor to users of Class1
). So while it's not ideal to friend the entirety of Class1
, it'd do in a pinch.
Thanks in advance.