【发布时间】: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