目前我有这一个排序功能: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