Ayr*_*lin 3 c++ templates template-argument-deduction
我想要我的模板功能
template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
return call(10, 10);
}
Run Code Online (Sandbox Code Playgroud)
以便能够接收指向函数的指针并稍后调用此函数。这段摘录是正确的,编译器不会抱怨错误。让我们考虑这样的程序
#include <iostream>
#include <string>
template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
return call(10, 10);
}
int main()
{
std::cout << probe([](int a,int b){ return a-b;});
}
Run Code Online (Sandbox Code Playgroud)
该程序输出我所期望的:零。但是,我为这个调用明确表示了我正在传递的函数 - 我的意思是括号中的这个 lambda 表达式[](int a,int b){ return a-b;}。这很好,直到我什么也没传递 - 调用std::cout << probe();不正确,但是我预计该函数将使用 default function function call = [] (int a, int b) { return a+b; }。那么,如何调用该函数的实例将在声明中使用默认 lambda 表达式的函数?
默认函数参数不参与模板参数推导。function当没有明确给出函数参数时,编译器无法推断,因此调用站点无法与任何要调用的函数匹配。
让您的示例工作的一种非常直接的方法是重载。
template<class function>
int probe(function call)
{
return call(10, 10);
}
inline int probe()
{
return probe([] (int a, int b) { return a+b; });
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |