为什么 std::function 不能接受推导类型作为其模板参数
Why can std::function not accept a deduced type as its template parameter?
#include <functional>
using namespace std;
template<class CharType>
void f1(CharType* str, function<bool(CharType)> fn_filter)
{}
template<class CharType>
void f2(CharType* str, function<bool(char)> fn_filter)
{}
void f3(char* str, char c)
{
auto fn_filter = [=](char e) -> bool
{
return e == c;
};
f1(str, fn_filter); // error C2784
f2(str, fn_filter); // OK
}
int main()
{
f3("ok", 'k');
}
// error C2784: 'void f1(CharType *,std::function<bool(CharType)>)'
// : could not deduce template argument for 'std::function<bool(CharType)>'
// from 'f2::<lambda_36be5ecc63077ff97cf3d16d1d5001cb>'
我的编译器是VC++ 2013。
为什么f1
不能按预期工作?
lambda 没有类型 std::function<bool(char)>
,它只是一些具有实现定义类型的可调用对象。
它可以转换为 std::function<bool(char)>
,但这无助于编译器推断模板大小写的类型。例如,可能有很多可能性CharType
可以将lambda转换为std::function<bool(CharType)>
。
编译器尝试将 lambda 的类型与模板函数的参数进行匹配。例如,lambda 具有类似 lambda_t_1234
的类型,模板参数为 std::function<bool(CharType)>
。这些类型是不相关的,目前尚不清楚CharType
应该在这里是什么。
这对 lambda 或 std::function<>
来说也不是特别的。在所有此类情况下都会发生同样的情况:
template<typename Char>
void f(const std::basic_string<Char> &str) {
}
如果尝试使用 char*
参数调用此模板函数,它将不起作用,因为与模板参数的连接不清楚。
编译器的问题是决定将哪些参数用于类型推导。如果您通过破坏第二个参数的可能推导来帮助编译并强制它使用第一个参数,则它会按预期工作:
template<typename T> struct identity { using type = T; };
template<class CharType>
void f1(CharType* str, typename identity<function<bool(CharType)>>::type fn_filter)
{}
现场示例
相关文章:
- 为什么 std::function 可以作为 std::not2 的参数?
- 传递给std::function template的template参数究竟代表什么
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 可变参数模板参数扩展 类型为 std::function 的类成员
- std::function<void()> 接受参数
- 在标准中,模板参数的语法在哪里定义,例如,'std::function<int(char)>'?
- C++派生类重载函数(带有 std::function 参数)不可见
- C++ 事件管理器的回调,使用 std::function 和 std:bind 以及派生类作为参数
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- C++初始化 std::function 时如何将占位符绑定到引用/引用参数?
- 仅当一个参数中未使用 std::function 时,模板函数替换才有效
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 将另一个类的成员函数传递到 std::function 参数中
- 如何返回用参数包定义的成员函数的std::function对象
- 了解 std::function 的晦涩模板参数
- 将 std::function* 传递给模板参数
- 构造函数模板参数推导,其中 std::function 作为参数
- 使用"std::function"和先前推断的模板参数替换失败 - 为什么?
- 使用 std::function 作为具有任意数量参数的数据成员
- 将可变参数函数参数转发到 std::function 对象