gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:36:07 26 4
gpt4 key购买 nike

几天我确实发现 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com