c++ - 将 std::function 与模板一起使用

标签 c++ templates std-function template-argument-deduction

所以在最精炼的形式中,我有这样的事情发生,

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/

相关文章:

C++11 将 std 函数绑定(bind)到重载的静态方法

c++ - 为什么我不能用它自己移动构造一个 unique_ptr?

c++ - C++中未定义数量的参数

C++ - 获取模板的类型名称,其中该类用作另一个模板

c++ - Microsoft Visual Studio 单元测试的 C2338 编译错误

c++ - 在编写包装现有函数并检查错误的模板函数时,如何使用完美转发?

node.js - 如何使查询结果可从所有页面访问

c++ - 使用派生类中的成员在父类中初始化 std::function

c++ - 参数类型 void*& 是什么意思,有什么用?

c++ - 非常量引用绑定(bind)到临时的 Visual Studio 错误?