简体   繁体   English

为两种不同类型专门化相同的模板定义

[英]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 .我无法控制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我想到的特定应用程序是fmt::formatter专业化,如下所示: 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:如果您查看fmt/core.hstruct formatter的定义,它有一个虚拟的typename = void参数:

template <typename T, typename Char = char, typename Enable = void>
struct formatter

This dummy parameter allows you to do SFINAE in specializations:这个虚拟参数允许你在专业化中做 SFINAE:

template <typename T>
struct formatter<T, char, std::enable_if_t<std::is_same_v<T, A> || std::is_same_v<T, B>>>
{
    // ...
};

The only duplication you could avoid in your presented code is the std::cout << std::endl;您在呈现的代码中可以避免的唯一重复是 std::cout << std::endl; You are outputting 'x' in both but they are of two different types so that is hardly duplication.您在两者中都输出 'x' 但它们是两种不同的类型,因此几乎不会重复。 If the duplication were actually enough to be concerned over you could create a shared base and have both specializations derive from that.如果重复实际上足以引起关注,您可以创建一个共享基础,并从中衍生出两个专业。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM