Meditation, The Art of Exploitation

Thinking? At last I have discovered it--thought; this alone is inseparable from me. I am, I exist--that is certain. But for how long? For as long as I am thinking. For it could be, that were I totally to cease from thinking, I should totally cease to exist....I am, then, in the strict sense only a thing that thinks.

Thursday, December 14, 2006

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.