Why does this not work (in C++11) and how can I fix it:
#include <iostream>
#include <functional>
using namespace std;
template <typename T>
int apply(string x, const function<int(T)>& fn)
{
T t = { x };
return fn(t);
}
struct S {
string data;
};
int process_s(const S& s)
{
return s.data.size();
}
int main()
{
cout << apply("abc", process_s);
}
The error is
prog.cc:21:8: error: no matching function for call to 'apply'
cout<<apply("abc", process_s);
^~~~~
prog.cc:7:5: note: candidate template ignored:
could not match 'function<int (type-parameter-0-0)>'
against 'int (const S &)'
int apply(string x, const function<int(T)>& fn) {
^
1 error generated.
I tried the approach from here, but it doesn't work either:
#include <iostream>
#include <functional>
using namespace std;
template <typename T>
struct id {
typedef T type;
};
template <typename T>
using nondeduced = typename id<T>::type;
template <typename T>
int apply(string x, const function<nondeduced<int(T)> >& fn)
{
T t = { x };
return fn(t);
}
struct S {
string data;
};
int process_s(const S& s)
{
return s.data.size();
}
int main()
{
cout << apply("abc", process_s);
}
Aucun commentaire:
Enregistrer un commentaire