我正在尝试使用模板定义一个函数,并且我希望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-17 17:15:22
除了非C++20的答案之外,如果您碰巧能够使用C++20及其concepts特性,我建议您使用以下实现:
#include <iostream>
#include <concepts>
enum class MyEnum {
A,
B,
C
};
template <typename T>
concept IntegralOrEnum = std::same_as<MyEnum, T> || std::integral<T>;
template <IntegralOrEnum T>
bool isFunction(T const& aVariable) {
return true;
}
int main() {
isFunction(MyEnum::A);
isFunction(3);
isFunction("my_string"); // error
return 0;
}更新
根据@RichardSmith的评论,这里有一个更具伸缩性和可重用性的方法:
template <typename T, typename ...U>
concept one_of = (std::is_same_v<T, U> || ...);
template <one_of<int, MyEnum> T>
bool isFunction(T const& aVariable) {
return true;
}发布于 2020-02-17 17:07:27
有几种方法可以做到这一点。所有这些都涉及到使用type_traits标头。例如,您可以在函数体中对相关类型进行静态断言。
或者,如果您需要在其他重载中考虑此功能,则可以使用SFINAE技术。
template<typename T>
auto isFunction(const T &aVariable)
-> std::enable_if_t<std::is_same<T, int>::value || std::is_same<T,anEnum>::value, bool> {
}如果类型不匹配,这将在调用之前从重载集中删除该函数。但是,如果您不需要此行为,则静态断言确实允许更多程序员友好的错误消息。
发布于 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
复制相似问题