【发布时间】:2022-01-24 02:50:50
【问题描述】:
考虑一下:
template <class T_arr, class T_func>
void iter(T_arr *arr, int len, T_func func)
{
for(int i = 0; i < len; i++)
{
func(arr[i]);
}
}
void display(int a) {
std::cout << "Hello, your number is: " << a << std::endl;
}
int main(void)
{
int arr[] = {1, 2, 3};
iter(arr, 3, display);
return (0);
}
但是,如果我尝试将显示功能更改为模板,则可以按预期工作:
template <class T>
void display(T a) {
std::cout << "Hello, your number is: " << a << std::endl;
}
它停止工作,我收到此错误:候选模板被忽略:无法推断模板参数“T_func”。
如何理解这一点?
【问题讨论】:
-
当您致电
iter(arr1, 3, display);时,哪个display是什么意思?display<int>?display<std::string>?display<double>?编译器无法弄清楚“哦,T_func应该接受T_arr作为其参数,所以因为我已经推断出T_arr = int,我将尝试为T_func实例化double<int>。
标签: c++ templates arguments parameter-passing