【发布时间】:2020-06-01 04:14:55
【问题描述】:
我正在尝试使用模板定义一个函数,并且我希望类型名是 int 或 anEnum(我已定义的特定枚举)。我尝试了以下方法,但失败了:
template <int | anEnum T> // or <int T, anEnum T> or <int, anEnum T>
bool isFunction(const T &aVariable){}
我想做的是使用模板,而不是定义两个重载函数。 我更喜欢按如下方式调用函数,而程序员不必考虑类型
isFunction(aVariable) // and not isFunction<int> (aVariable) nor isFunction<anEnum> (aVariable)
基本上,我希望将此函数模板化为 int 和 aNum 类型。我已经搜索过这个,但找不到答案。我可能会错过什么?谢谢,
【问题讨论】:
-
如果恰好是单个枚举或int类型,为什么不简单地编写两个函数呢?为什么在这种情况下需要模板?
-
其他类型呢?你想为其他类型返回
false还是不想为其他类型实例化函数。 -
@frogatto 不,bool 返回值没有任何类型。
-
@Klaus 我已经要求学习替代方案。根据当前的答案,我决定简单地定义这两个函数。
标签: c++ templates overloading