泛型枚举和其他类型的重载模板函数

Overload template function for generic enum and the other types

本文关键字:重载 函数 类型 枚举 其他 泛型      更新时间:2023-10-16

我有一个适用于任何类型的枚举的泛型函数。我想用自定义类以及字符串和整数重载它。但是,我会收到函数过载错误消息。我该如何解决这个问题?

错误:重载的"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);
}