首页 > 解决方案 > 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

标签: c++

解决方案


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>>>
{
    // ...
};

推荐阅读