Currently I have this for a sorting function:
bool operator()( CVParent* lhs, CVParent* rhs )
{
double dFirstValue = reinterpret_cast< CVChild * >( lhs )->GetValue( m_lFeature );
double dSecondValue = reinterpret_cast< CVChild * >( rhs )->GetValue( m_lFeature );
....
}
Right now the type-id is hardcoded as CVChild* but can it be a parameter? I don’t want to be writing a function for every derived classes of CVParent.
Edit:
I have made changes based on Rost’s recommendation:
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;
}
Current Usage (how to do revised the stl sort function call?):
std::sort( m_pList, m_pList+GetCOunt(), Compare_Functor(lFeature, TRUE) );
I fixed the code. Thank you for everyone’s help!
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) );
It’s not possible to pass any dynamic (known in run time only) type to
reinterpret_cast. It must be static (known in compile time).You could use templates as mentioned in other answer, but you will need to explicitly set the type to cast for each function call because compiler will not be able to deduce it from call expression: