【问题标题】:Why we use non-type template arguments?为什么我们使用非类型模板参数?
【发布时间】:2012-09-23 07:02:14
【问题描述】:

我理解这个概念,但我不知道为什么我需要使用非类型模板参数?

【问题讨论】:

标签: c++ templates arguments


【解决方案1】:

有很多用例,让我们来看看它们必不可少的几种情况:

  • 固定大小的数组或matrix 类,例如参见C++11 std::array 或boost::array。

  • std::begin 用于数组的可能实现,或任何需要固定大小的 C 样式数组大小的代码,例如:

返回数组的大小:

template <typename T, unsigned int N>
unsigned int size(T const (&)[N])
{
  return N;
}

它们在模板元编程中也非常有用。

【讨论】:

    【解决方案2】:

    一个真实的例子来自结合非类型模板参数和模板参数推导来推导数组的大小:

    template <typename T, unsigned int N>
    void print_array(T const (&arr)[N])       // both T and N are deduced
    {
        std::cout << "[";
        for (unsigned int i = 0; i != N; ++i)
        {
            if (i != 0) { std::cout << ", ";
            std::cout << arr[i];
        }
        std::cout << "]";
    }
    
    int main()
    {
        double x[] = { 1.5, -7.125, 0, std::sin(0.5) };
        print_array(x);
    }
    

    【讨论】:

      【解决方案3】:

      在编译时编程。考虑WikiPedia 的例子,

      template <int N>
      struct Factorial {
          enum { value = N * Factorial<N - 1>::value };
      };
      
      template <>
      struct Factorial<0> {
          enum { value = 1 };
      };
      
      // Factorial<4>::value == 24
      // Factorial<0>::value == 1
      const int x = Factorial<4>::value; // == 24
      const int y = Factorial<0>::value; // == 1
      

      维基百科页面上还有很多其他示例。

      编辑

      如 cmets 中所述,上面的示例演示了 可以做什么,而不是 人们在实际项目中使用什么。

      【讨论】:

      • 我不了解你,但“我们”不会在编译时使用它来编程。 :\
      • 这只是展示了模板的强大功能,并没有展示它们如何在实际代码中使用。
      • 我在 SO 的某处看到了 Bounded Integer 类,但现在找不到。它允许创建自定义类型,例如 bounded&lt;0, 255&gt;。
      • @hwd 第一个链接是最近的。但我记得看到type conversions 和bounded&lt;int, ...&gt; 与int 一样完美地实现了相同的更完整 实现。
      【解决方案4】:

      另一个非类型参数的例子是:

      template <int N>
      struct A
      {
          // Other fields.
          int data[N];
      };
      

      这里数据字段的长度是参数化的。此结构的不同实例化可以具有不同长度的数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多