我写了一个简单的例子,它以某种方式编译。
#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
中的评论。
第三,非整型模板参数的模板函数存在的原因是什么?它与具有常规功能有何不同?
最佳答案
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
这里被推导为传递的数组的大小。
关于c++ - 非类型模板参数与函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34384407/