你能帮我理解为什么这段代码不能编译吗?我正在尝试理解 C++ 模板。
#include <iostream>
#include <algorithm>
#include <vector>
template <class myT>
void myfunction (myT i)
{
std::cout << ' ' << i;
}
int main ()
{
double array1[] = {1.0, 4.6, 3.5, 7.8};
std::vector<double> haystack(array1, array1 + 4);
std::sort(haystack.begin(), haystack.end());
std::cout << "myvector contains:";
for_each (haystack.begin(), haystack.end(), myfunction);
std::cout << '\n';
return 0;
}
最佳答案
因为你路过 myfunction
对于一个函数,它无法计算出自动使用哪个模板,所以你必须用 myfunction<double>
告诉它
这在直接调用时不适用,例如 myfunction(2.0)
因为为了方便起见,编译器会根据您提供的参数确定使用哪个模板。
关于c++ - 函数模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15306722/