C++ const reference and template generic programming
Consider that you are required to write a min function (not macro), in C++ the best approach would be to use a template function to write the min function once for all:
inline template < typename>
T min(T const& a, T const& b) { return a < b? a: b; }
However there is a subtle issue here with const reference argument when it comes to character array literals. To quote Noah Roberts from CLC++:
The problem has to do with how character arrays get resolved per
reference vs. value. For example you wouldn't be able to pass two
string literals of different length to that function:
char * x = min("hello", "hell");
Nope...won't work (not according to the book anyway).
Reason, becasue it is reference semantics it attempts to pass char[6]&
as first and char[5]& as second parameters...can't happen.
The way to fix this is to override for char*, which you have to do
anyway:
template<>
char* min(char* l, char* r) { ... do strcmp stuff...}
So, there is no "problem" to speak of, just something to be aware of.
inline template < typename>
T min(T const& a, T const& b) { return a < b? a: b; }
However there is a subtle issue here with const reference argument when it comes to character array literals. To quote Noah Roberts from CLC++:
The problem has to do with how character arrays get resolved per
reference vs. value. For example you wouldn't be able to pass two
string literals of different length to that function:
char * x = min("hello", "hell");
Nope...won't work (not according to the book anyway).
Reason, becasue it is reference semantics it attempts to pass char[6]&
as first and char[5]& as second parameters...can't happen.
The way to fix this is to override for char*, which you have to do
anyway:
template<>
char* min
So, there is no "problem" to speak of, just something to be aware of.
<< Home