Consider this template function:
template<class T, class F> inline
auto transform(const vector<T>& l, F func) -> vector<decltype(func(T{}))>
{
vector<decltype(func(T{}))> out(l.size());
std::transform(l.begin(), l.end(), out.begin(), func);
return out;
}
This function can be called as
auto out = transform(intputVector, functor)
functor has to be either static member fuction or a global function.
Is there a way to modify the above code to work on non-static member functions as well?
struct Test {
Test() {
vector<int> vx = { 1, 2, 3 };
auto vy1 = transform(vx, staticMemberFunc); // is fine
auto vy2 = transform(vx, memberFunc); // does not compile
}
flt memberFunc(int x) {
return 2 * x;
}
static flt staticMemberFunc(int x) {
return 2 * x;
}
};
您可以使用lambda绑定对象指针:
auto vy2 = transform(vx, [this](int x){return this->memberFunc(x);});
Yes,
std::bind()
to give you a functor which you can pass in
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.