xml*_*lmx 4 c++ templates types c++11 template-argument-deduction
#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>'
Run Code Online (Sandbox Code Playgroud)
我的编译器是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这里应该是什么.
这对lambdas或者也不是特别的std::function<>.所有这些情况都会发生同样的情况:
template<typename Char>
void f(const std::basic_string<Char> &str) {
}
Run Code Online (Sandbox Code Playgroud)
如果您尝试使用char*参数调用此模板函数,它将无法工作,因为与模板参数的连接不明确.
| 归档时间: |
|
| 查看次数: |
892 次 |
| 最近记录: |