目前我有一个排序功能:
bool operator()( CVParent* lhs, CVParent* rhs )
{
double dFirstValue = reinterpret_cast< CVChild * >( lhs )->GetValue( m_lFeature );
double dSecondValue = reinterpret_cast< CVChild * >( rhs )->GetValue( m_lFeature );
....
}
现在 type-id 被硬编码为 CVChild* 但它可以是一个参数吗?我不想为 CVParent 的每个派生类编写一个函数。
编辑:我根据 Rost 的建议进行了更改:
class Compare_Functor
{
public:
Compare_Functor( const long& lFeature, const bool& bIsAscending )
{
m_lFeature = lFeature;
m_bIsAscending = bIsAscending;
}
template <class T>
bool operator()( CVParent* lhs, CVParent* rhs )
{
double dFirstValue = reinterpret_cast< T * >( lhs )->GetValue( m_lFeature );
double dSecondValue = reinterpret_cast< T * >( rhs )->GetValue( m_lFeature );
....
}
private:
long m_lFeature;
bool m_bIsAscending;
}
当前用法(如何修改 stl 排序函数调用?):std::sort( m_pList, m_pList+GetCOunt(), Compare_Functor(lFeature, TRUE) );
我修复了代码。谢谢大家的帮助!
template <class T>
class Compare_Functor
{
public:
Compare_Functor( const long& lFeature, const bool& bIsAscending )
{
m_lFeature = lFeature;
m_bIsAscending = bIsAscending;
}
bool operator()( CVParent* lhs, CVParent* rhs )
{
double dFirstValue = reinterpret_cast< T * >( lhs )->GetValue( m_lFeature );
double dSecondValue = reinterpret_cast< T * >( rhs )->GetValue( m_lFeature );
....
}
private:
long m_lFeature;
bool m_bIsAscending;
}
//Usage
std::sort( m_pList, m_pList+GetCOunt(), Compare_Functor<CChild>(lFeature, TRUE) );