将 std::function 与模板一起使用

Using std::function with templates

本文关键字:一起 std function      更新时间:2023-10-16

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

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'没有匹配函数",无论我是否将变量作为常量引用传递或只是普通值或其他什么。我假设它无法推断出一些模板,但我不知道在哪里或为什么。

我承认,我对如何使用函数对象有非常微弱的把握,做这样的事情可能吗?

参数func声明为std::function,并且您正在尝试传递函数指针,这需要隐式转换。模板参数推导不考虑隐式转换,然后推导失败。

类型

推断不考虑隐式转换(上面列出的类型调整除外(:这是重载解决的工作,稍后会发生。

您可以显式构造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>);

我已经为您修复了一些问题并添加了一些示例。这应该可以帮助您了解如何使用简单的 std::function。

#include <iostream>
#include <string>
#include <functional>
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 a==b; // a simple comparator
}  
int main()
{
int a = 1;
int b = 1;
// instantiate f and g as integer type functions
if( f<int>(a,b,g<int>) == true) 
std::cout << "true" << std::endl;
else
std::cout << "false" << std::endl;
std::string c="dead";
std::string d="beef";
// and now as strings
if( f<std::string>(c,d,g<std::string>) == true) 
std::cout << "true" << std::endl;
else
std::cout << "false" << std::endl;
return 0;
}