I was using a preprocessor statement similar to yours except with parenthesis, however, I think that the pure C++ approach with inline functions is much more in the nature of good coding. The typedef with the function pointer came to mind actually but I decided not to do it because it's kinda messy with the extra variables and stuff.
The compile-time template parameter versus a runtime parameter is really a choice dependant on the usage of the function. This is a simple dumb little program for my C++ class I'm forced to take (there's no placement test and I already skipped the first two courses in the programming track). The templated function impressed a ton of people. And yeah, the speed difference is neglible too. It's probably better to make it a runtime parameter but who really cares.
If anybody is interested, here's that section of the code with tons of comments taken out for breivity. As you can tell, the implementation isn't messy at all.
Code:
// Returns the alphabetical absolute word of the sequence, depending on the direction.
// <compareDirection>: Positive stands for the greatest word, negative stands for the smallest word, alphabetically.
// wordsList: The sequence of words to process.
template <int compareDirection>
static string getAbsoluteWord(Sequence &wordsList)
{
// Set the first word of the sequence as the absolute word.
string absoluteWord = wordsList[0];
// Loop through all the words past the first one.
int count = wordsList.size();
for (int i = 1; i < count; ++i)
{
const string ¤tWord = wordsList[i];
int comparison = currentWord.compare(absoluteWord) * compareDirection;
// If this word is "greater" than the current absolute word, then it should be the new absolute word.
if (comparison > 0)
{
absoluteWord = currentWord;
}
}
return absoluteWord;
}
// Returns the smallest word in the sequence.
// wordsList: The sequence of words to process.
static inline string getSmallestWord(Sequence &wordsList)
{
return getAbsoluteWord <-1> (wordsList);
}
// Returns the largest word in the sequence.
// wordsList: The sequence of words to process.
static inline string getLargestWord(Sequence &wordsList)
{
return getAbsoluteWord <1> (wordsList);
}