c++std for_each稍后定义std函数
c++ std for_each define the std function later
我想更改此代码:
std::for_each( container.begin(), container.end(), std::bind(&Class::method1, _1, param));
其中容器有指向Class的指针,指向只会传递param:的版本
// create the functor here ( bind to method1 or method2, etc)
// ....
//
std::for_each( container.begin(), container.end(), functor(param) );
我不能用lambdas。
容器可以是:
std::list<Class*>
struct functor {
int param;
functor(int param): param(param) {}
void operator()(Class* c) {
c->method1(param);
}
};
给你。一个函子类,可以完全用作您的示例。没有lambda,就没有绑定到方法。只需将参数传递给构造函数。您可以将成员函数指针传递给构造函数,或者将其扩展到模板,以避免为每个方法编写一个指针。
或者,如果你只是想先选择方法,然后再绑定参数,你可以这样做:
// create the functor here ( bind to method1 or method2, etc)
std::function<void(Class*,decltype(param))> functor(&Class::method1); // "bind" the method
// ....
std::for_each( container.begin(), container.end(), std::bind(functor, _1, param) ); // bind the param
请注意,我认为这样做没有任何好处,而不是你问题中的第一行代码。
您想要一些东西来生成函子。
这是你想要的一般函子。
template< typename CLASS, typename CLASS_METHOD, typename PARAM_TYPE >
class Functor
{
CLASS_METHOD m_method; // actually will be of type void(CLASS::*func)( PARAM_TYPE )
PARAM_TYPE m_param;
public:
void operator()( CLASS * c ) const
{
(c->*m_method)( m_param );
}
};
template typename< CLASS, CLASS_METHOD, PARAM_TYPE >
Functor< CLASS, CLASS_METHOD, PARAM_TYPE >
functor( CLASS_METHOD method, PARAM_TYPE param )
{
return Functor< CLASS, CLASS_METHOD, PARAM_TYPE >( method, param );
}
std::for_each
(
container.begin(), container.end(),
functor< Class >( &Class::method1, param );
);
如果你愿意,我们可以让它成为非模板。
class Functor
{
typedef void (Class::*func_type )(int);
func_type m_method; // assuming that's the param type
int m_param;
public:
Functor( func_type method, int param )
: m_method( method ), m_param( param )
{
}
void operator()( Class * c ) const
{
(c->*m_method)(param);
}
};
std::for_each( container.begin, container.end(), Functor( &Class::method1, param ) );
现在,为了"仅"指定参数,您为每个"方法"编写函数,因此:
Functor method1Functor( int param )
{
return Functor( &Class::method1, param );
}
Functor method2Functor( int param )
{
return Functor( &Class::method2, param );
}
现在在您的代码中:
std::for_each( container.begin(), container.end(), method1Functor( param ) );
您也可以编写这些函数方法来执行bind
并返回std::function
。
相关文章:
- 为constchar*定义std::begin合法吗
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 在自定义 std::vector-like 容器中处理指针和非指针模板类型的最佳方法是什么?
- 自定义 std::fstream,std::filebuf 的溢出和下溢函数未为每个字符调用
- 运算符的歧义错误<<自定义 std::ostream 子类中的重载
- 自定义 std::shared_ptr 删除器
- "unix" C++预处理器宏未定义 -std=c++11
- C++ - 定义 std::array 类型的二维矩阵
- 为模板类嵌套类定义 std::hash 时出现编译错误
- 使用自定义deleter类型定义std::shared_ptr的别名
- 在C++中,为什么<cctype>同时定义std::isspace和::isspace?
- 定义 std::hash<std::function>
- 自定义 std::shared_ptr 或 boost::shared_ptr 以在 NULL 取消引用时引发异常
- 重新定义 std::hash 模板结构
- 如何在自定义 std::ostream 类中使用 std::endl
- 为类模板的枚举成员定义 std::hash
- 如何在另一个类数据成员上定义“std::set”排序
- 定义 std::字符串 C++不带转义字符
- 如何实现自定义 std::streambuf 的 seekoff()?
- 如何使用自定义std::sort函数