【问题标题】:non-type template parameter vs function parameter非类型模板参数 vs 函数参数
【发布时间】:2015-12-20 18:36:34
【问题描述】:

我写了一个简单的例子,它以某种方式编译。

#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;
}

这个例子让我很沮丧:

首先,我给模板提供了非类型模板参数,但没有提供任何参数(在括号中)来函数本身。貌似模板参数变成了函数参数,为什么呢?

其次,即使它编译,我也找不到使用此模板的方法,请参阅main中的我的cmets。

第三,模板函数存在非整型模板参数的原因是什么?它与具有常规功能有什么不同?

【问题讨论】:

  • 顺便说一句,不要使用 endl。它很慢,因为每次使用时都必须刷​​新缓冲区。 "\n" 速度更快,大多数语言的程序员都能理解,不仅仅是 C++

标签: c++ templates parameters arguments


【解决方案1】:

int A 不是函数参数,它是模板参数。 func 不接受任何参数,您可以像这样实例化/调用它:

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

请查看 C++ 函数模板。你不能以你想要的方式使用模板参数。

另一方面,有一个类型模板参数和一个函数参数:

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

将使您的程序有效。也许这就是你想要的。

编辑:

应您的要求,以下是此类非类型函数模板参数的用法:

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

std::array版本:

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

S这里推导出传入数组的大小。

【讨论】:

  • LogicStuff,我同意你所说的。但是如何允许在模板函数定义中使用模板参数,就像它是一个函数参数一样?我的意思是那些cout &lt;&lt; 1 + A &lt;&lt; endl; 行。
  • 通过func&lt;1&gt;,函数将在编译时被实例化,如下所示:cout &lt;&lt; 1 + 1 &lt;&lt; endl;。这是编译时的问题。
  • 非常感谢。您能否给出一个场景,当具有整数类型的非类型模板参数的模板函数可能有用时?
猜你喜欢
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
相关资源
最近更新 更多