试图编写一个函数来实现标题所说的功能:
template<class T>
function<string(int)> conv(function<T(int)> f) {
return [&](int x) -> string {
stringstream ss;
ss << f(x);
return ss.str();
};
}
clang 抛出此错误:
prog.cpp:28:3: error: no matching function for call to 'conv'
conv(f1),
^~~~
prog.cpp:17:23: note: candidate template ignored: could not match 'function<type-parameter-0-0 (int)>' against 'int (*)(int)'
function<string(int)> conv(function<T(int)> f) {
或者这只是用宏完成的?
完整代码:
#include <iostream>
#include <functional>
#include <sstream>
#include <vector>
using namespace std;
int f1(int x) {
}
string f2(int x) {
}
long long f3(int x) {
}
template<class T>
function<string(int)> conv(function<T(int)> f) {
return [&](int x) -> string {
stringstream ss;
ss << f(x);
return ss.str();
};
}
int main() {
vector<function<string(int)>> funcs = {
conv(f1),
};
return 0;
}
问题是您的参数
conv不会自动转换为std::function,您要么需要更改函数本身:或将函数参数包装在
std::function:考试