【发布时间】:2016-09-13 10:17:14
【问题描述】:
我有一个通常返回整数的函数,但由于值的语义可能不同,我想对它们进行强类型,所以我引入了两种类型,例如金钱和时间,简化为
struct Money {
uint32_t value;
}
该函数将根据 bool 参数返回 Money 或 Time。假设它看起来像这样:
template <typename T> T getValue(bool mode) {
Money money;
Time time;
...
if (mode == ModeMoney) {
money = something * 2;//get it from somewhere - irrelevant for the example
return money;
}
if (mode == ModeTime) {
time = something * 100;
return time;
}
}
现在编译器会抱怨不同的返回类型,所以我添加了专门的模板函数来返回值本身:
template <> Money variableValue<Money>(something) { return something * 2 };
template <> Time variableValue<Time>(something) { return something * 100};
这允许在调用时删除 bool 参数,主函数现在将更改为:
template <typename T> T getValue(bool mode) {
....//calculation of *something* is the same, we only need different output from the function
return variableValue<T>(something);
}
这是一个好方法吗?
【问题讨论】:
-
如果你的函数有不同的逻辑和不同的返回类型,为什么不把它拆分成两个函数呢?
-
用例是什么?根据您使用
getValue的方式,有几种替代方案可能会更好 -
我发布的示例非常简化,这可能会造成混淆。逻辑其实是一样的,写两个函数只会复制两个不同输出的逻辑