所以在最精炼的形式中,我有这样的事情发生,
template <class T>
bool f(const T &a, const T &b, std::function<bool(const T&, const T&)> func)
{
return func(a,b);
}
template <class T>
bool g(const T &a, const T &b)
{
return true;
}
但是任何调用 f()
的尝试,f('a', 'b', g)
, f(1, 2 , g)
,总是导致“没有匹配的函数调用‘f’”,无论我是将变量作为 const 引用传递还是只是普通值或其他什么。我假设它无法推断出某些模板,但我不知道在哪里或为什么。
我承认,我对一般情况下如何使用函数对象的把握非常薄弱,这样做有可能吗?
最佳答案
参数 func
被声明为 std::function
,并且您试图传递一个函数指针,这需要隐式转换。 Template argument deduction不考虑隐式转换,推导失败。
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
您可以显式构造一个std::function
,
f('a', 'b', static_cast<std::function<bool(const char&, const char&)>>(g<char>));
或者显式指定模板参数(绕过模板参数推导,使隐式转换稍后生效),
f<char>('a', 'b', g<char>);
或者干脆不使用 std::function
。
template <class T, class F>
bool f(const T &a, const T &b, F func)
{
return func(a,b);
}
f('a', 'b', g<char>);
关于c++ - 将 std::function 与模板一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52508593/