Typedef模板功能
问题描述:
鉴于我有一个由枚举模板化的函数,我想“typedef/alias”函数来简化它的使用。这里类似的问题:(Typedef with template functions,C++11: How to alias a function?)Typedef模板功能
这里有三种可能的解决方案,我想出了,而且我不喜欢他们:
- 写宏包的功能。问题:宏(命名空间安全性?)
- 静态函数指针。问题:变量(例如,需要添加#pragma部分以禁用Wunused变量)
- 为每种情况明确写入函数。问题:创建全新的功能(即不只是重命名原有的功能),更易于出错的写入,更多的函数调用
- 与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);
}
答
如果你的目的是要分数添加到一个整数,并将结果存储在一个整数中,最简单的做法是创建一个可以像0123那样调用的函数它的可读性很好。另外,我讨厌宏。
int add_score(int previous_score, Score score);
模板与非类型模板参数并不在我看来
感谢这里提高可读性。诚然,这也是我最初的功能正在做的事情(除了写入指针与返回值)。这里的评分例子只是一个代码片段,但我需要的真实应用程序有点复杂。 – Cedric
@Cedric能否详细说明你的真实用例如何比你提出的问题更复杂?这可能会影响我的回答 – Curious
我有一个框架与不同的模块,由ModuleID(枚举)标识。然后我有转换功能,它需要数据来自哪里以及去哪里的地方。 AddData(module_id源,module_id本地,数据)。 我想为每个模块提供一个版本,所以我可以在模块“home”中的任何地方都可以说AddDataHome(module_id source,data),而不必每次都传递它自己的id。 – Cedric