c++ - 函数模板

标签 c++ templates

你能帮我理解为什么这段代码不能编译吗?我正在尝试理解 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/

相关文章:

c++ - 在 C++11 中使函数模板参数无符号

javascript - 如何将脚本传递给 main.scala.html - Play ! 2个

c++ - 使用 boost::python 从 C++ 创建 python collections.namedtuple

C++线程问题

C++:如何构建两个空格分隔字符串的交集字符串?

c++ - 这个模板函数是在哪里生成的呢?可以通过 g++ 编译,但不能在 Visual Studio 中编译

c++ - Clang 与 MSVC : Treatment of template function prototypes

c++ - 为什么我们不能在内联命名空间之外声明演绎指南?

c++ - 如何使用不同版本的 mingw 构建的静态库?

c++ - 如何将 unique_ptr 与更通用的删除器一起使用?