我写了一个简单的例子,它以某种方式被编译。
#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中的评论。
第三,非整型模板参数的模板函数存在的原因是什么?它和普通的函数有什么不同?
发布于 2015-12-21 02:43:13
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被推导为传递的数组的大小。
https://stackoverflow.com/questions/34384407
复制相似问题