简体   繁体   English

非类型模板参数vs函数参数

[英]non-type template parameter vs function parameter

I wrote a trivial example, which is somehow compiles. 我写了一个简单的示例,该示例以某种方式可以编译。

#include <iostream>
using namespace std;

template <int A>
void func()
{
    cout << 1 + A << endl;
    return;
}

int main()
{
    // I can not even use this strange func()
    int a = 1; func(a); // this does not compile
    func(1);            // this does not compile as well 
    return 0;
}

This example frustrates me a lot: 这个例子让我很沮丧:

First, I gave non-type template parameter to template, but did not provide any parameters (in parentheses) to function itself. 首先,我给模板提供了非类型模板参数,但没有提供任何参数(在括号中)以实现自身功能。 Looks like template parameter becomes the function parameter, but why? 看起来模板参数成为函数参数,但是为什么呢?

Second, even though it compiles, I can not find a way to use this template, see my comments in main . 其次,即使它可以编译,我也找不到使用此模板的方法,请参阅main注释。

And third, what is the reason for existence of template functions with non-type template parameter of integral type? 第三,存在具有整数类型的非类型模板参数的模板函数的原因是什么? How is it any different from having a regular function? 与具有常规功能有什么不同?

int A is not a function parameter, it's a template parameter. int A不是函数参数,它是模板参数。 func takes no arguments and you instantiate/call it like this: func不带参数,您可以这样实例化/调用它:

func<1>(); // compile-time constant needed

Please review C++ function templates. 请查看C ++函数模板。 You can't use template parameters in the way you want. 您不能以所需的方式使用模板参数。

On the other hand, having a type template parameter and one function parameter: 另一方面,具有类型模板参数和一个功能参数:

template <typename A>
void func(A a)
{
    cout << 1 + a << endl;
}

will make your program valid. 将使您的程序有效。 Maybe that's what you wanted. 也许这就是您想要的。

Edit: 编辑:

To your request, here's a usage of such non-type function template parameter: 根据您的要求,以下是此类非类型函数模板参数的用法:

template <size_t S>
void func(const int (&array)[S])
{
    cout << "size of the array is: " << S << endl;
}

or std::array version: std::array版本:

template <size_t S>
void func(std::array<int, S> const& array)
{
    cout << "size of the array is: " << S << endl;
}

S here is deduced to the size of the passed array. 这里的S被推导为传递数组的大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM