Given that I have a function templated by an enum, I would like to "typedef/alias" the function to simplify its usage. Similar questions here: (Typedef with template functions, C++11: How to alias a function?)
Here are three possible solutions I came up with, and what I do not like about them:
- Write a macro wrapping the functions. Issue: macro (namespace safety?)
- Static function pointer. Issue: variable (e.g. need to add #pragma sections to disable Wunused-variable)
- Write function explicitely for each case. Issue: Creation of completely new function (i.e. not just renaming of original one), more writing prone to errors, more function calls
- Same as 3., but inline to keep in header. This is probably my favourite. Issue: Creation of completely new function (i.e. not just renaming of original one), more function calls
Are there other particular advantages / disadvantages of the methods listed above (apart from personal dislike)? Should some be avoided at all cost?
Dummy Example:
foo_lib.h
#ifndef _FOO_LIB_H_
#define _FOO_LIB_H_
enum class Score {
LOSS = 0,
DRAW = 1,
WIN = 3
};
void AddScore(int *current_score_p, const Score &score);
template <Score SCORE>
void AddScore(int *current_score_p) {
AddScore(current_score_p, SCORE);
}
// 1. macro
#define ADD_SCORE_DRAW(current_score_p) AddScore<Score::DRAW>((current_score_p))
// 2. static function pointer (auto would work too)
static void (*AddScoreDrawStatic)(int *current_score_p) = &AddScore<Score::DRAW>;
// 3. Explicit function for each case
void AddScoreDrawSpecial(int *current_score_p);
// 4. Like 3., but inline to keep in header
inline void AddScoreDrawInline(int *current_score_p) { AddScore<Score::DRAW>(current_score_p); }
#endif // _FOO_LIB_H_
foo_lib.cpp
#include "foo_lib.h"
void AddScore(int *current_score_p, const Score &score) {
*current_score_p += static_cast<int>(score);
}
void AddScoreDrawSpecial(int *current_score_p) {
AddScore<Score::DRAW>(current_score_p);
}