c++ - Template parameters dilemma -
i have dilemma. suppose have template class:
template <typename valuet> class array { public: typedef valuet valuetype; valuetype& getvalue() { ... } };
now want define function receives reference class , calls function getvalue(). consider following 2 ways:
method 1:
template <typename valuetype> void dogetvalue(array<valuetype>& arr) { valuetype value = arr.getvalue(); ... }
method 2:
template <typename arraytype> void dogetvalue(arraytype& arr) { typename arraytype::valuetype value = arr.getvalue(); ... }
there no difference between 2 methods. calling both functions same:
int main() { array<int> arr; dogetvalue(arr); }
now, of 2 best? can think of cons , pros:
method 1 pros:
the parameter real class not template, easier user understand interface - explicit parameter has array. in method 2 can guess name. use valuetype in function more clear way when hidden inside array , must accessed using scope operator.
in addition typename keyword might confusing many non template savvy programmers.
method 2 pros:
this function more "true" purpose. when think if it, don't need class array. need class has method getvalue , type valuetype. that's all. is, method more generic.
this method less dependent on changes in array class. if template parameters of array changed? why should affect dogetvalue? doesn't care how array defined.
evey time have situation i'm not sure choose. choice?
if function specific arraytype
, , no other template satisfy interface requirements, use #1 it's both shorter , more specific: casual reader informed operates on arraytype
.
if there's possibility other templates compatible dogetvalue
, use #2 it's more generic.
but no use obsessing, since it's easy enough convert between them.
Comments
Post a Comment