C/C++ — Friends and Templates

by

In C++, if you declare a template class and you would like to have a friend function that has an argument of the current class type, you need to be careful when specifying the name of the template types. For example:

template <class T>
class A {

template <class T>
friend void b(A<T> a);
} ;

Will confuse the compiler, as you use the same template name, T, for the class template and the function template type. What you need to do, it to use a different name for the function template type:

template <class T>
class A {

template <class V>
friend void b(A<V> a);
} ;

Notice that I used T for the class template type and V for the function template type.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: