c++ - 自动插入模板参数?

标签 c++ templates

几天我确实发现 C++ 的一种行为,模板参数会自动插入,如本例所示(无意义,仅用于说明我的意思):

#include <iostream>

template<typename Type> void setVar(Type& subj, const Type& in)
{
    subj = static_cast<Type>(in);
}

int main()
{
    int foo;
    setVar(foo, 42);
    std::cout << foo << std::endl;
}

我的问题:

  • 这种行为叫什么?
  • 何时以及为什么可以自动插入模板是否有特殊规则?

最佳答案

What is this behaviour called?

模板参数推导。

are there special rules when and why templates can be automatically inserted?

你不能说 templates are inserted。相反,参数的类型是从参数中自动推导出来的。何时以及如何?这就是 TAD 的意义所在。

查看 C++03 中的 14.8.2 部分

关于c++ - 自动插入模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4134840/

相关文章:

c++ - 从线程抛出异常没有给出预期的结果

c++ - 具有相同名称的静态变量的开关案例的单独范围

c++ - 来自特征 MatrixXcd 的角度数据

templates - Go 模板 : How do I access array item (arr[2]) in templates?

c++ - 带map的模板参数初始化列表

c++ - 如何创建多个模板对象的数组

c++ - 如何在 Linux 上的 C++ 程序中使用 yaml-cpp?

指向具有(虚拟)继承的模板类的 C++ 指针

c++ - C++ 强制转换重载运算符的问题

javascript - JQuery Masonry 是怎么来的,当我在浏览器上单击 "back"时,它会将用户射回顶部?