使用std :: function的模板替换失败 [英] Template substitution failure with std::function
问题描述
我试图将回调函数作为函数参数传递。但是在以下代码中出现模板替换失败错误。不确定为什么模板替换失败。
I am trying to pass a callback function as function parameter. But getting template substitution failure errors in following code. Not sure why template substitution is failing.
#include<iostream>
#include <map>
#include <tuple>
#include <functional>
template<typename A,typename B>
void myfun(std::map<A,B> & mm, std::function<std::tuple<A,B>(void)> fn)
{
A key;
B val;
std::tie(key,val) = fn();
mm[key] = val;
}
std::tuple<std::string,int> fun()
{
return std::make_tuple(std::string("hi"),1);
}
int main()
{
std::map<std::string,int> gg;
#if 0
//fixed version
std::function<std::tuple<std::string,int>(void)> yy = fun;//fixed
myfun(gg,yy);//fixed
#else
// error causing code
myfun(gg,fun);
#endif
}
错误如下
main.cpp:8:6: note: template argument deduction/substitution failed:
main.cpp:25:17: note: mismatched types 'std::function<std::tuple<_T1, _T2>()>' and 'std::tuple<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, int> (*)()'
myfun(gg,fun);
推荐答案
编译器不能同时转换为 std :: function
并推导出模板参数。它不理解任意函数指针和 std :: function
之间的映射。
The compiler can't both cast to a std::function
and deduce the template arguments. It doesn't understand the mapping between an arbitrary function pointer and a std::function
.
有一个
您可以在呼叫站点上显式创建 std :: function
:
You could explicitly create a std::function
at the call site:
myfun(gg,std::function<std::tuple<std::string,int>(void)>{fun});`
您可以编写 make_function
函数为您推断类型。您可以在网上找到有关此主题的讨论和实现,例如在此处,此处和
You could write a make_function
function to deduce the types for you. You can find discussions and implementations of this online, such as here, here and here.
myfun(gg,make_function(fun));
您可能会忘记 std :: function
并推导出整个函数类型。这是我要采用的方法:
You could just forget about std::function
and deduce the entire function type. This is the approach I would take:
template<typename A,typename B, typename Fun>
void myfun(std::map<A,B> & mm, Fun fn)
{
A key;
B val;
std::tie(key,val) = fn();
mm[key] = val;
}
这篇关于使用std :: function的模板替换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!