【发布时间】:2017-06-28 08:25:55
【问题描述】:
鉴于我有一个由枚举模板化的函数,我想“typedef/alias”该函数以简化其使用。类似的问题在这里:(Typedef with template functions, C++11: How to alias a function?)
以下是我想出的三种可能的解决方案,以及我不喜欢它们的地方:
- 编写一个封装函数的宏。问题:宏(命名空间安全?)
- 静态函数指针。问题:变量(例如,需要添加 #pragma 部分以禁用 Wunused-variable)
- 为每种情况明确编写函数。问题:创建全新的函数(即不仅仅是重命名原来的函数),更容易出错,更多的函数调用
- 与 3. 相同,但内联保留在标题中。这可能是我最喜欢的。问题:创建全新的函数(即不仅仅是重命名原来的函数),更多的函数调用
上面列出的方法是否还有其他特别的优点/缺点(除了个人不喜欢)?是否应该不惜一切代价避免一些?
虚拟示例:
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);
}
【问题讨论】:
标签: c++ templates alias typedef