【发布时间】:2015-03-23 02:20:30
【问题描述】:
这是一个完整的小程序。对test1() 和test2() 的前三个调用编译并正常运行,对test2() 的最后一个调用没有编译。如何在不指定调用类型的情况下让编译器识别对 test2() 的调用?
#include <functional>
#include <iostream>
// using function pointer
template <typename T>
T test1(T arg, T (*fnptr)(T)) {
return fnptr(arg);
}
// using a lambda
template <typename T>
T test2(T arg, std::function<T (T)> mapfn) {
return mapfn(arg);
}
int dbl(int v) {
return 2 * v;
}
int main() {
// v1a: compiles, runs without error
int v1a = test1<int>(11, dbl);
std::cout << v1a << std::endl;
// v2a: compiles, runs without error
int v2a = test2<int>(11, [=](int arg) { return 2 * arg; });
std::cout << v2a << std::endl;
// v1b (without template type): compiles, runs without error
int v1b = test1(11, dbl);
std::cout << v1b << std::endl;
// v2a (without template type): doesn't compile: no matching fn
int v2b = test2(11, [=](int arg)->int { return 2 * arg; });
std::cout << v2b << std::endl;
return 0;
}
编译器生成以下消息:
$ g++ -O3 -Wall -std=c++11 -o sketch_tiny sketch_tiny.cpp
sketch_tiny.cpp:34:13: error: no matching function for call to 'test2'
int v2b = test2(11, [=](int arg)->int { return 2 * arg; });
^~~~~
sketch_tiny.cpp:12:3: note: candidate template ignored: could not match
'function<type-parameter-0-0 (type-parameter-0-0)>' against '<lambda at
sketch_tiny.cpp:34:23>'
T test2(T arg, std::function<T (T)> mapfn) {
^
1 error generated.
有没有办法让编译器在不使用test2<int>(...) 类型说明符的情况下识别对test2(...) 的调用?
不管怎样,编译环境如下:
$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn)
Target: x86_64-apple-darwin14.1.0
Thread model: posix
【问题讨论】:
-
不同的是,lambda不是
std::function,而是dbl衰减为函数指针。 -
@T.C.为什么不能只从第一个参数中进行推断?
-
T.C.:我同意最初的问题类似于stackoverflow.com/questions/9998402/…。我已经重新措辞了这个问题以提出真正的问题:如何强制编译器匹配模板函数中的 lambda? 虽然我现在知道答案(使用具有两种类型的模板,即
template <typename T, typename MapFn>),这个问题应该重新打开,因为答案通常很有用(你真的必须挖掘才能在另一个问题中找到答案)。
标签: c++ templates c++11 lambda function-pointers