Search code examples
c++templatesfriend

Why template function cannot be a friend template function of a template class?


I was following a video tutorial and I want to declare a template function as a friend of a template class. I don't know why code is throwing error.

template<class T>class C;
template<class T>void doSomething2(T);
template<class T>class C{
    int b;
    friend void doSomething2(T);

};
template<class U>void doSomething2(U u){
    C<U> obj;
    obj.b=100;
}
int main()
{
    C<int> obj;
    int a=44;
    doSomething2(a);
    return 0;
}

and compiler was throwing error.

Error :

templates_friends_38.cpp: In instantiation of ‘void doSomething2(T) [with T = int]’: templates_friends_38.cpp:40:19: required from here templates_friends_38.cpp:32:9: error: ‘int C::b’ is private within this context obj.b=100; ~~~~^ templates_friends_38.cpp:25:9: note: declared private here int b; ^


Solution

  • You need to add <> in a friend declaration to specify that doSomething2 is a template function:

    template<class T>class C;
    template<class T>void doSomething2(T);
    template<class T>class C{
        int b;
        friend void doSomething2<>(T);
    
    };
    template<class U>void doSomething2(U u){
        C<U> obj;
        obj.b=100;
    }
    int main()
    {
        C<int> obj;
        int a=44;
        doSomething2(a);
        return 0;
    }