[英]Transform vectory by non-static member function
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 使用std::bind()
给你一个函子,你可以传入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.