Vladimir Jovic said:
Ian said:
Hi
Could somebody tell me why this doesn't compile:
#include<iostream>
using namespace std;
template <typename T>
class matrix
{
public:
friend matrix<T> operator+<>(const matrix<T>&, const matrix<T>&);
};
int main (int argc, char const *argv[])
{
matrix<int> m;
return 0;
}
I get the following error:
error: template-id ¡®operator+<>¡¯ for ¡®matrix<int> operator+(const
matrix<int>&, const matrix<int>&)¡¯ does not match any template
declaration
gcc's warning is clearer:
You have to declare the function template before the friend declaration.
template <typename T> class matrix;
template <typename T> matrix<T> operator+(const matrix<T>&, const
matrix<T>&);
template <typename T>
class matrix
{
public:
friend matrix<T> operator+<>(const matrix<T>&, const matrix<T>&);
};
Which way is better? The above with forward declaration, or as in the
example bellow?
template <typename T>
class matrix
{
public:
template <typename T1>
friend matrix<T1> operator+(const matrix<T1>&, const matrix<T1>&);
};
int main (int argc, char const *argv[])
{
matrix<int> m;
}
You're aware, of course, that this second version is not the same as the
first in a significant (and possibly relevant) way?
Remember, that classes instantiated from class templates and functions
instantiated from function templates are all different. Your first
definition specifies that, given a particular instantiation matrix<type>,
then friendship is granted so that an op+<type> can have priviledged
access to the private and protected internals of matrix<type>. The
second, however, goes further and grants friendship in this sense to
*all* instantiations of op+<T1> for any one instantiation of
matrix<type>. Does it make sense, in the second instance, to have
op+<float> be a friend of matrix<int>?
On the basis that good design should only break the tightest
encapsulation where it really must, I would suggest that the second goes
too far, even though it is hard at a casual glance to envisage a
scenario in which an implementation of matrix might fall fowl of such a
widening of permissiveness.
Regards
Paul Bibbings