具有成员变量和方法默认值的模板 class 专业化

Template class specialization with default value for member variables and methods

我有一个 class 模板:

template<typename T>
struct DefaultPattern {
  using type = int;
  static int CalculateValue(const T& input) {
    return 0;
  }
};

对于每种类型T,我都会有一个专长。问题是在特化 class 中,我需要定义在 DefaultPattern 中定义的所有成员变量和方法,即使它们可能与 DefaultPattern。这是一个例子:

// A specialization for int.
template<>
struct DefaultPattern<int> {
  // Same as DefaultPattern but I need to define it again.
  using type = int;
  static int CalculateValue(const int& input) {
    return input + 2;
  }
};

有没有办法让我做特化的时候只需要定义 那些不同于DefaultPattern的成员?

Is there a way so that when I do the specialization, I only need to define those members that are different from DefaultPattern?

一种可能的解决方案是一种自我继承:您的专业化可以从通用模板继承。请注意,为了从通用模板继承,特化使用特定的实例化(例如下面使用 T = long)。

例如:

template <>
struct DefaultPattern<int> : public DefaultPattern<long>
 {
   static int CalculateValue (int const & input)
    { return input + 2; }
 };

所以DefaultPattern<int>DefaulPattern<long>(或DefaultPattern<std::string>或其他东西)继承type = int并重新定义CalculateValue()

以下是完整的工作示例:

#include <iostream>
#include <type_traits>

template <typename T>
struct DefaultPattern
 {
   using type = int;

   static int CalculateValue (T const &)
    { return 0; }
 };

template <>
struct DefaultPattern<int> : public DefaultPattern<long>
 {
   static int CalculateValue (int const & input)
    { return input + 2; }
 };

int main ()
 {
   static_assert( std::is_same<DefaultPattern<int>::type, int>{}, "!" );

   std::cout << DefaultPattern<long>::CalculateValue(1L) << std::endl;
   std::cout << DefaultPattern<int>::CalculateValue(1) << std::endl;
 }