我正在尝试使用模板定义一个函数,并且我希望typename为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类型的模板。我已经找过了,但是找不到答案。我可能遗漏了什么?谢谢,
发布于 2020-02-18 06:11:31
这个解决方案怎么样?如果类型T满足您的要求,则将编译带有该函数的代码。否则,静态断言将失败。
#include <type_traits>
enum anEnum {
//
};
template <typename T, bool defined = std::is_same<T, int>::value ||
std::is_same<T, anEnum>::value>
bool isFunction(const T& aVariable)
{
static_assert(defined, "Invalid specialization");
bool result = false;
// Put your code here
return result;
}https://stackoverflow.com/questions/60258919
复制相似问题