Here's a small program in its entirety. The first three calls to test1()
and test2()
compile and run properly, the last call to test2()
doesn't compile. How can I get the compiler to recognize the call to test2() without specifying the type in the call?
#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;
}
The compiler generates the following message:
$ 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.
Is there a way to get the compiler to recognize the call to test2(...)
without using the test2<int>(...)
type specifier?
For what it's worth, here's the compilation environment:
$ 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