我有一个类(class)模板:

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

对于每种类型T,我都会有一个专长。问题是,在特化类中,我需要定义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不同的成员?

最佳答案



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

例如:

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

因此,DefaultPattern<int>type = int(或DefaulPattern<long>或其他)继承DefaultPattern<std::string>并重新定义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;
 }

09-06 08:04