为什么我可以这样做:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void myfunction (int i) {
cout << " " << i;
}
int main () {
vector<int> myvector;
myvector.push_back(10);
myvector.push_back(20);
myvector.push_back(30);
cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myfunction);//<-------See below
return 0;
}
但不能这样做:
template<class T>
void myfunction (T i) {
cout << " " << i;
}
我怀疑它与 args 推导有关,但令人气愤的是“常规”fnc 被接受而模板不被接受。
最佳答案
问题是您无法创建指向模板函数的指针。不过,您应该能够创建一个指向实例化模板函数的指针。我没试过这个,但以下应该有效:
for_each (myvector.begin(), myvector.end(), myfunction<int>)
关于c++ - 模板问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3751580/