目前我有這一個排序功能:reinterpret_cast < type-id >的「type-id」是否是一個變量?
bool operator()(CVParent* lhs, CVParent* rhs)
{
double dFirstValue = reinterpret_cast< CVChild * >(lhs)->GetValue(m_lFeature);
double dSecondValue = reinterpret_cast< CVChild * >(rhs)->GetValue(m_lFeature);
....
}
眼下型-ID被硬編碼爲CVChild *,但它可以是一個參數?我不想爲CVParent的每個派生類寫一個函數。
編輯:基於羅斯特的建議 我做了更改:
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 ::排序(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));
你可以給你的原因,你要使用'reinterpret_cast'? – evnu
1. IIRC(我現在沒有檢查過)它可以是模板參數。 2.你確定你想要'reinterpret_cast'(在大多數情況下,演員不是最好的編程風格,除非真的需要,否則應該避開它們)? –
不,我想使用reinterpret_cast,但傳入的類型被轉換爲變量。 – AvatarBlue