使用非类型模板参数而不是常规参数的原因? [英] Reason for using non-type template parameter instead of regular parameter?

查看:94
本文介绍了使用非类型模板参数而不是常规参数的原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,您可以使用非类型模板参数创建模板,如下所示:

In C++ you can create templates using a non-type template parameter like this:

template< int I >
void add( int& value )
{
  value += I;
}

int main( int argc, char** argv )
{
  int i = 10;
  add< 5 >( i );
  std::cout << i << std::endl;
}

这将打印15这有什么用?是否有任何理由使用非类型的模板参数,而不是更传统的方式:

Which prints "15" to cout. What is the use for this? Is there any reason for using a non-type template parameter instead of something more conventional like:

void add( int& value, int amount )
{
  value += amount;
}

对不起,如果这已经被问了)。

Sorry if this has already been asked (I looked but couldn't find anything).

推荐答案

非类型模板参数有很多应用程序;这里有一些:

There are many applications for non-type template arguments; here are a few:

您可以使用非类型参数来实现表示固定大小的数组或矩阵的通用类型。例如,您可以在其尺寸上参数化 Matrix 类型,因此可以使 Matrix <4,3> Matrix <2,2> 。如果随后为这些类型正确定义重载运算符,则可以防止意外错误添加或乘以不正确维度的矩阵,并且可以创建明确传达其接受的矩阵的预期维度的函数。

You can use non-type arguments to implement generic types representing fixed-sized arrays or matrices. For example, you might parameterize a Matrix type over its dimensions, so you could make a Matrix<4, 3> or a Matrix<2, 2>. If you then define overloaded operators for these types correctly, you can prevent accidental errors from adding or multiplying matrices of incorrect dimensions, and can make functions that explicitly communicate the expected dimensions of the matrices they accept. This prevents a huge class of runtime errors from occur by detecting the violations at compile-time.

您可以使用非类型参数通过模板实现编译时函数评估元编程。例如,下面是一个在编译时计算阶乘的简单模板:

You can use non-type arguments to implement compile-time function evaluation through template metaprogramming. For example, here's a simple template that computes factorial at compile-time:

template <unsigned n> struct Factorial {
    enum { 
       result = n * Factorial<n - 1>::result
    };
};
template <> struct Factorial<0> {
    enum {
       result = 1
    };
};

这样可以编写 Factorial< 10> :: result 在编译时获取值10!这可以防止在运行时执行额外的代码。

This allows you to write code like Factorial<10>::result to obtain, at compile-time, the value of 10!. This can prevent extra code execution at runtime.

此外,您可以使用非类型参数来实现编译时维度分析,它允许您定义千克,米,秒等的类型,以便编译器可以确保您'

Additionally, you can use non-type arguments to implement compile-time dimensional analysis, which allows you to define types for kilograms, meters, seconds, etc. such that the compiler can ensure that you don't accidentally use kilograms where you meant meters, etc.

希望这有助于!

这篇关于使用非类型模板参数而不是常规参数的原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆