Now i am quite confused about template
we are supposed to use it for some sort of paramiterized stuff,
template f(T)
however, if more than one classes can be fed to a certain function, they must
share certain similar properties and thus can be modeled as a hierarchy. Then
we can just define the function as f(class A) where A is the base.
Then , is template only useful in containers?
can anyone give me some corrections?
thanks lot!
a**a 发帖数: 416
2
You never heard of specialization? suggest you study the parameter
matching order of templated functions.
【在 mw 的大作中提到】 : Now i am quite confused about template : we are supposed to use it for some sort of paramiterized stuff, : template f(T) : however, if more than one classes can be fed to a certain function, they must : share certain similar properties and thus can be modeled as a hierarchy. Then : we can just define the function as f(class A) where A is the base. : Then , is template only useful in containers? : can anyone give me some corrections? : thanks lot!
g*****g 发帖数: 34805
3
It's good to have compiler check as much as possible and as early as
possible. At the same time, we want to have flexibility.
template will make perfect sense in Collection classes, for example,
Vector is way better than Vector
a**n 发帖数: 313
4
I think you can understand template as another kind of polymorphism.
Usually polymorphism refers to inheritance and virtual functions.
【在 mw 的大作中提到】 : Now i am quite confused about template : we are supposed to use it for some sort of paramiterized stuff, : template f(T) : however, if more than one classes can be fed to a certain function, they must : share certain similar properties and thus can be modeled as a hierarchy. Then : we can just define the function as f(class A) where A is the base. : Then , is template only useful in containers? : can anyone give me some corrections? : thanks lot!
X****r 发帖数: 3557
5
Template in C++ is a (rough) realization of generic programming,
which is totally a different approach against object-oriented programming.
Also, as a side effect, template allows (limited) compile-time computation.
Nevertheless, your question is a good one. Whether it's better to use
templates or polymorphism for a function or an algorithm really depends
on individual situation.
For example, let's say your function is to quick-sort. The most basic
implementation only requires the elements being
【在 mw 的大作中提到】 : Now i am quite confused about template : we are supposed to use it for some sort of paramiterized stuff, : template f(T) : however, if more than one classes can be fed to a certain function, they must : share certain similar properties and thus can be modeled as a hierarchy. Then : we can just define the function as f(class A) where A is the base. : Then , is template only useful in containers? : can anyone give me some corrections? : thanks lot!