合并一组模板专用化

merge a group of template specializations

本文关键字:专用 一组 合并      更新时间:2023-10-16

我有 3 个函数模板专用化,代码完全相同。我已经尝试了一段时间,但无法成功将它们合并到单个模板表达式中。下面是一个示例:

template <typename Event>
void aFunction(const Event &anEvent){
// do nothing for other types
}
template <>
void aFunction(const InsertEvent &anEvent){
std::cout<<"aFunction"<<std::endl;
}
template <>
void aFunction(const RemoveEvent &anEvent){
std::cout<<"aFunction"<<std::endl;
}
template <>
void aFunction(const ChangeEvent &anEvent){
std::cout<<"aFunction"<<std::endl;
}

编辑: 我尝试使用 std::enable_if_t 合并它们,并且我已经能够按以下步骤进行:

template <typename Event>
typename std::enable_if_t<
!std::is_same<Event, InsertEvent>::value &&
!std::is_same<Event, RemoveEvent>::value &&
!std::is_same<Event, ChangeEvent>::value>
aFunction(const Event &anEvent){
// do nothing for other types
}
template <typename Event>
typename std::enable_if_t<
std::is_same<Event, InsertEvent>::value ||
std::is_same<Event, RemoveEvent>::value ||
std::is_same<Event, ChangeEvent>::value>
aFunction(const Event &anEvent){
std::cout<<"aFunction"<<std::endl;
}

相反,是否有可能摆脱 !std::is_same<..更通用的模板案例>行?

这是一种可能的方法:

template <typename Event>
void aFunction(const Event &anEvent, std::false_type){
// do nothing for other types
}
template <typename Event>
void aFunction(const Event &anEvent, std::true_type){
std::cout<<"aFunction"<<std::endl;
}
template <typename Event>
void aFunction(const Event &anEvent){
aFunction(anEvent, std::integral_constant<bool, 
std::is_same_v<Event, InsertEvent> ||
std::is_same_v<Event, RemoveEvent> ||
std::is_same_v<Event, ChangeEvent>>{});
}

演示