[
next
] [
prev
] [
prev-tail
] [
tail
] [
up
]
1.1.17.3
template and friend
There are three different kinds for a template class: non-template friend, Bound-template, unbound-template. Below is non-template friend function counts(); The counts is not invoked by an HasFriend obj.
template
<
typename
T
>
class
HasFriend
{
friend
void
counts
();
}
Bound-template friend function. You need to define explicit specialization for the friends you plan to use.
template
<
typename
T
>
class
HasFriend
{
friend
void
reports
(
HasFriend
<
T
>
&);
}
void
reports
(
HasFriend
<
int
>
&
hf
){
cout
<<
hf
.
item
<<
endl
;
}
void
reports
(
HasFriend
<
short
>
&
hf
){..}
void
reports
(
HasFriend
<
char
>
&
hf
){..}
//
explicit
specialization
for
the
type
you
plan
to
use
.
A better bound-template, reports has <> after it. and you don’t need redifne reports many time like previous codes.
1)
template
<
typename
T
>
void
report
(
T
&);
2)
template
<
typename
TT
>
class
HasFriend
{
friend
void
reports
<>(
HasFriend
<
TT
>
&);
}
3)
template
<
typename
T
>
void
reports
(
T
&
hf
){
cout
<<
hf
.
item
<<
endl
;
}
non-bound friend template.
template
<
typename
T
>
class
ManyFriend
{
template
<
typename
C
,
typename
D
>
friend
void
show
(
C
&
,
D
&);
};
template
<
typename
C
,
typename
D
>
void
show2
(
c
&
c
,
D
&
d
){
cout
<<
c
.
item
<<
d
.
item
<<
endl
;
}
ManyFriend
<
int
>
mi
;
ManyFriend
<
double
>
md
;
show2
(
mi
,
md
);
[
next
] [
prev
] [
prev-tail
] [
front
] [
up
]