【问题标题】:Template class specialization with default value for member variables and methods具有成员变量和方法的默认值的模板类特化
【发布时间】:2018-04-28 09:59:36
【问题描述】:

我有一个类模板:

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的成员?

【问题讨论】:

  • 不相关,但为什么是 using type = int; ?你永远不会在任何地方使用type
  • @JesperJuhl 它可以很容易地知道在decltype(foo)::type; 或其他模板参数不是很明显的情况下给出的类型。就像std::vector&lt;T&gt;::value_type 总是T 一样。
  • 这只是我从真实代码中简化的一个例子。我可以从另一个类调用 DefaultPattern::type 或 DefaultPattern::type。变量类型不需要是我们特化的 T。
  • 特化是一个单独的类型,所以不会“继承”任何东西。您可以拥有一个公共基类,其中包含始终相同的事物。
  • 看起来这是CRTP 的工作。

标签: c++ templates template-specialization


【解决方案1】:

有没有办法让我在进行专业化时,只需要定义那些不同于 DefaultPattern 的成员?

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

例如:

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

所以DefaultPattern&lt;int&gt;DefaulPattern&lt;long&gt;(或DefaultPattern&lt;std::string&gt;或其他)继承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;
 }

【讨论】:

    猜你喜欢
    • 2023-03-20
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多