【发布时间】:2015-10-13 09:34:11
【问题描述】:
我正在尝试将回调函数作为函数参数传递。但是在以下代码中出现模板替换失败错误。不确定模板替换失败的原因。
#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);
【问题讨论】:
-
"hi"可能会被推导出为const char*,尝试使用std::string("hi") -
std::function和普通函数是不同的东西,见stackoverflow.com/questions/9054774/…。 -
@JohannesWalcher 或者更好的
"hi"s使用 C++14