将 std::function 与模板一起使用
Using std::function with templates
所以在最提炼的形式中,我有这样的事情发生,
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;
}
相关文章:
- 将fold表达式与std::一起用于两个元组
- 将 std::allocate_shared 与多态资源分配器一起使用
- 将 std::set 与基于键的比较器一起使用
- 如何将AERT_Allocate与 std:vector 一起使用
- 将用户定义的类型与 std::vector 和 std::sort 一起使用
- 将图形属性与 std::unique_ptr 捆绑在一起
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- 将新放置与 std::函数一起使用不起作用
- 不能将C++的"std::filesystem"库与介子构建一起使用
- 将 std::function 与模板一起使用
- 是否可以将 std::basic_ifstream 和 std::basic_ofstream 与自定义缓冲区一起使用?
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 如何将 std::find() 与 2d std: 数组一起使用?
- boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- 将 std::transform 与 std::back_inserter 一起使用是否有效?
- 为什么使用与父级声明的 std::function 在与子级一起使用时会显示错误?
- 是否已经有一个 constexpr std::bit_cast 与 g++ 一起使用
- 将 std::variant 与 gmock 1.8 对象一起使用时编译错误
- 我不能将 'fill' std::vector 构造函数与 unique_ptrs 一起使用