c++ - Specializing The Same Template Definition For Two Different Types
问题描述
I am trying to specialize the same template for two different classes in the following way:
template <>
struct TemplateClass<A> {
void method(A x) {
std::cout << x << std::endl;
}
};
template <>
struct TemplateClass<B> {
void method(B x) {
std::cout << x << std::endl;
}
};
Is there a way I can rewrite this to avoid the duplication inside the two specialization definitions?
I do not have control over the definition of TemplateClass
. The particular application I have in mind is specialization of fmt::formatter
as shown here:
https://fmt.dev/latest/api.html#formatting-user-defined-types
解决方案
If you look at the definition of struct formatter
in fmt/core.h
, it has a dummy typename = void
parameter:
template <typename T, typename Char = char, typename Enable = void>
struct formatter
This dummy parameter allows you to do SFINAE in specializations:
template <typename T>
struct formatter<T, char, std::enable_if_t<std::is_same_v<T, A> || std::is_same_v<T, B>>>
{
// ...
};
推荐阅读
- android - React 本机应用程序适用于调试模式,但不适用于 android 的发布模式
- vue.js - Vue如何在v-for循环中获取每个youtube视频的持续时间
- python - 同一个函数可以有不同的返回值吗?
- json - 如何使用方法名称 { "GROUP(date)": "2019-09"} 之类的键遍历 JSON 对象 - 芭蕾舞演员
- javascript - 如何使用 JS 中的值,而不是从 HTML 中获取值?
- android - 文件路径的位图 decodefile() 显示为空
- python - 机器学习代理合作推送块不返回奖励
- mongodb - 尽管 expireAt 已通过,但文档未删除
- mysql - 获取 MySQL JSON 数组字段以加入表
- python-3.x - 如何捕获行的块