泛型枚举和其他类型的重载模板函数
Overload template function for generic enum and the other types
我有一个适用于任何类型的枚举的泛型函数。我想用自定义类以及字符串和整数重载它。但是,我会收到函数过载错误消息。我该如何解决这个问题?
错误:重载的"show_value(MyAlpha("的调用不明确
魔杖盒
#include <type_traits>
#include <iostream>
#include <string>
using namespace std;
enum MyAlpha
{
ALPHA,
BETA
};
enum Animal
{
ELEFANT,
GOAT,
RABIT
};
class MyClass
{
public:
string text;
MyClass(string text): text(text) {}
};
template<typename T, typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>
void show_value(T x) { cout<<"Enum: "<<(int)x<<endl; };
void show_value(int x) { cout<<"Int: "<<x<<endl; };
void show_value(string x) { cout<<"String: "<<x<<endl; };
template<class T>
void show_value(T x) { cout<<"Obj.text: "<<x.text<<endl; };
int main()
{
show_value(MyAlpha(BETA));
show_value(Animal(RABIT));
show_value(5);
show_value("Rainy day");
show_value(MyClass("Waterfall"));
return 0;
}
你应该使SFINAE的重载相互排斥。否则,对于enum
类型,两个模板化重载完全匹配。
例如
template<typename T, typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>
void show_value(T x) { cout<<"Enum: "<<(int)x<<endl; };
template<class T, typename std::enable_if<!std::is_enum<T>::value>::type* = nullptr>
void show_value(T x) { cout<<"Obj.text: "<<x.text<<endl; };
住
PS:"Rainy day"
不是std::string
型,而是const char[]
型。所以把show_value("Rainy day");
改成show_value(std::string("Rainy day"));
.
template<typename T, typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>
void show_value(T x)
并不比(包罗万象(更专业
template<class T> void show_value(T x);
所以用enum
打电话是模棱两可的。
您必须丢弃非枚举的通用版本:
template<typename T, typename std::enable_if<!std::is_enum<T>::value>::type* = nullptr>
void show_value(T x) { std::cout << "Obj.text: " << x.text << std::endl; };
或者给他们一个优先权。
struct low_priority_overload {};
struct high_priority_overload : low_priority_overload{};
// Or use template <std::size_t N> struct priority_overload : priority_overload<N - 1>{}
template<typename T, typename std::enable_if<std::is_enum<T>::value>::type* = nullptr>
void show_value_impl(high_priority_overload, T x) { cout<<"Enum: "<<(int)x<<endl; };
void show_value_impl(high_priority_overload, int x) { cout<<"Int: "<<x<<endl; };
void show_value_impl(high_priority_overload, string x) { cout<<"String: "<<x<<endl; };
template<class T>
void show_value_impl(low_priority_overload, T x) { cout<<"Obj.text: "<<x.text<<endl; };
template<class T>
void show_value(T x)
{
show_value_impl(high_priority_overload{}, x);
}
相关文章:
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 可以打印矢量和矢量中的矢量的非重载C++函数
- 错误 没有与参数列表匹配的重载函数"getline"实例
- 使用模板重载函数
- C++线程中,没有重载函数接受 X 参数
- std::vector 没有重载函数的实例与参数列表匹配
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- 错误:无法解析对重载函数的引用;你的意思是调用它吗?
- 对重载函数find_first_not_of的不明确调用
- 如何从重载解析中删除重载函数?
- CUDA:重载函数"isnan"的多个实例
- C++派生类重载函数(带有 std::function 参数)不可见
- 避免在人为的重载函数调用中拼写出类型
- C++:如何为多个重载函数保留通用代码路径?
- 什么时候可以使用常量装饰调用我的重载函数?
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- std::调用,未找到匹配的重载函数
- 为什么在传递长整型时调用具有两个双精度类型的参数的重载函数?
- 为什么使用不匹配的参数调用重载函数仍然有效
- 如何通过签名作为模板参数来解决重载函数?