[
next
] [
prev
] [
prev-tail
] [
tail
] [
up
]
1.3.5
Template example
.h file. They can be compiled wit -std=c++11
template
<
class
X
,
class
Y
>
class
my2D
{
X
x
;
Y
y
;
public
:
my2D
(
X
x
,
Y
y
){
this
-
>
x
=
x
;
this
-
>
y
=
y
;
}
X
getX
();
Y
getY
();
};
//
create
a
new
template
class
my2D_child
which
inherits
from
//
this
template
with
new
member
function
length
(),
template
<
class
X
,
class
Y
>
class
my2D_child
:
my2D
<
X
,
Y
>
{
public
:
my2D_child
(
X
x
,
Y
y
)
:
my2D
<
X
,
Y
>::
my2D
(
x
,
y
){}
auto
length
()
-
>
decltype
(
my2D
<
X
,
Y
>::
x
+
my2D
<
X
,
Y
>::
y
);
};
//
write
a
template
specilization
of
my2D_child
for
string
template
<>
class
my2D_child
<
std
::
string
,
std
::
string
>
:
my2D
<
std
::
string
,
std
::
string
>{
public
:
my2D_child
(
std
::
string
x
,
std
::
string
y
)
:
my2D
<
std
::
string
,
std
::
string
>::
my2D
(
x
,
y
){}
void
length
(){
std
::
cout
<<
getX
()<<
getY
()
<<
std
::
endl
;}
};
.cpp file.
//
file
my2D
.
cpp
#
include
"
my2D
.
h
"
#
include
<
iostream
>
using
namespace
std
;
//
impletment
the
function
getX
in
file
my2D
.
cpp
template
int
my2D
<
int
,
int
>::
getX
();
template
float
my2D
<
float
,
float
>::
getX
();
template
<
class
X
,
class
Y
>
X
my2D
<
X
,
Y
>::
getX
(){
return
x
;
};
//
implement
this
length
function
of
my2D_child
to
return
x
*
x
+
y
*
y
template
int
my2D_child
<
int
,
int
>::
length
();
template
<
class
X
,
class
Y
>
//
C
++14
has
new
syntax
auto
(
decltype
).
auto
my2D_child
<
X
,
Y
>::
length
()
-
>
decltype
(
my2D
<
X
,
Y
>::
x
+
my2D
<
X
,
Y
>::
y
){
return
my2D
<
X
,
Y
>::
getX
()
*
my2D
<
X
,
Y
>::
getX
()
+
my2D
<
X
,
Y
>::
getY
()
*
my2D
<
X
,
Y
>::
getY
();
};
int
main
(){
//
to
use
this
my2D
template
for
cases
(
X
=
int
(3),
Y
=
int
(4))
//
,
(
X
=
float
(5.5),
Y
=
float
(6.6),
my2D
<
int
,
int
>
my_int_2d
(3,4);
my2D
<
float
,
float
>
my_float_2d
(5.5,
6.6);
cout
<<
my_int_2d
.
getX
()<<
endl
;
my2D_child
<
int
,
int
>
my_int_child_2d
(3,4);
cout
<<
my_int_child_2d
.
length
()<<
endl
;
//
print
an
output
of
my2D_child
’
s
length
for
//
(
X
="
I
need
",
Y
="
Time
to
finish
")
my2D_child
<
string
,
string
>
ms_2d_child
(
"
I
␣
need
"
,
"
time
"
);
ms_2d_child
.
length
();
return
0;
}
[
next
] [
prev
] [
prev-tail
] [
front
] [
up
]