user5826166
user5826166

Reputation:

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

Upvotes: 3

Views: 255

Answers (2)

songyuanyao
songyuanyao

Reputation: 172894

friend void doSomething2(T);, you're declaring a new non-template function named doSomething2 as friend, which is not the one you expected.

You need to specify that doSomething2 is a function template, e.g.

friend void doSomething2<T>(T);
//                      ^^^

Or take advantage of template argument deduction and just write

friend void doSomething2<>(T);
//                      ^^

LIVE

Upvotes: 4

Dmitry Gordon
Dmitry Gordon

Reputation: 2324

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

Upvotes: 4

Related Questions