[英]how can I refactor a container to use a predicate method directly?
The snippet below works. 以下代码段有效。 However, it's a bit ugly because it uses a static method to wrap a method call to a predicate.
但是,这有点丑陋,因为它使用静态方法将方法调用包装到谓词。
In other words, I would like to replace: 换句话说,我想替换为:
c.remove_if_true( Value::IsOdd ); // static method
with something like 用类似的东西
c.remove_if_true( Value::isOdd ); // member method
There should be one fewer level of indirection and hopefully, the resultant code would be clearer. 间接访问的级别应该少一些,希望最终的代码会更清晰。
How do I refactor my code to call isOdd()
directly without having to go through a static method wrapper? 如何重构代码以直接调用
isOdd()
而不需要通过静态方法包装器?
However, if this implementation is as clear as I can make this code, also let me know. 但是,如果此实现可以使我清楚地实现此代码,则也请告知我。 TIA.
TIA。
#include <vector>
#include <functional>
template< typename T >
class MyContainer
{
public:
typedef std::function<bool(const T& t)> PREDICATE;
public:
void remove_if_true( PREDICATE predicate )
{
// NOTE: use implementation from KennyTM's answer below
}
private:
std::vector< T > m_vec;
};
class Value
{
public:
Value( int i ) : m_i( i ) { }
bool isOdd() const { return m_i%2==1; }
static bool IsOdd( const Value& v ) { return v.isOdd(); }
private:
int m_i;
};
int main()
{
MyContainer<Value> c;
c.remove_if_true( Value::IsOdd ); // would like to replace with Value::isOdd here
}
ataylor's suggestion std::mem_fun_ref()
required with gcc 4.6.1 and other compilers not completely up-to-date with latest standards gcc 4.6.1和其他编译器要求的ataylor建议
std::mem_fun_ref()
并非最新标准的最新版本
#include <vector>
#include <algorithm>
#include <functional>
template< typename T >
class MyContainer
{
public:
typedef std::const_mem_fun_ref_t<bool, T> PREDICATE;
public:
void remove_if( PREDICATE predicate )
{
auto old_end = m_vec.end();
auto new_end = std::remove_if(m_vec.begin(), old_end, predicate);
m_vec.erase(new_end, old_end);
}
private:
std::vector< T > m_vec;
};
class Value
{
public:
Value( int i ) : m_i( i ) { }
bool isOdd() const { return m_i%2==1; }
private:
int m_i;
};
int main()
{
MyContainer<Value> c;
c.remove_if( std::mem_fun_ref( &Value::isOdd ));
}
c.remove_if_true( std::bind( &Value::isOdd, _1 ) );
c.remove_if_true( std::mem_fn(&Value::isOdd) );
BTW, is there any reason you need to avoid std::remove_if
? 顺便说一句,有什么理由需要避免
std::remove_if
吗?
void remove_if_true(PREDICATE predicate)
{
auto old_end = m_vec.end();
auto new_end = std::remove_if(m_vec.begin(), old_end, predicate);
m_vec.erase(new_end, old_end);
}
您可以使用std::mem_fn_ref
包装isOdd
:
c.remove_if_true( std::mem_fun_ref(&Value::isOdd) );
Best way use lambdas : 最好的使用lambdas的方法:
c.remove_if_true( [] (const Value & v) { return v.get() % 2 == 0; } );
Or more self-commented : 或更自我评论:
auto isOdd = [] (const Value & v) { return v.get() % 2 == 0; };
c.remove_if_true( isOdd );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.