reinterpret_cast<类型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的每个派生类编写一个函数。

编辑:我根据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) );

不可能将任何动态(仅在运行时中已知)类型传递给reinterpret_cast。它必须是静态的(在编译时已知)。

您可以使用其他答案中提到的模板,但您需要为每个函数调用显式设置要强制转换的类型,因为编译器将无法从调用表达式中推断出它:

template <class T> struct Functor
{
   bool operator()(CVParent* lhs, CVParent* rhs) { ... }
};
CVParent p1, p2;
...
// Usage
Functor<CVChild1>().operator()(&p1, &p2);
Functor<CVChild2>().operator()(&p1, &p2);
Functor<CVChild3>().operator()(&p1, &p2);

您始终可以在实现中使用模板。

template <class Type>
bool operator()( CVParent* lhs, CVParent* rhs ) 
{
  double dFirstValue  = reinterpret_cast< Type * >( lhs )->GetValue( m_lFeature );
  double dSecondValue = reinterpret_cast< Type * >( rhs )->GetValue( m_lFeature );
  ....
}

我建议使用模板,但使用类模板,而不是函数模板。这将使在标准库算法和连接器中使用更加自然:

template <typename T>
struct CVFuntor 
{
  bool operator()( CVParent* lhs, CVParent* rhs ) const
  {
    double dFirstValue  = reinterpret_cast<T*>( lhs )->GetValue( m_lFeature );
    double dSecondValue = reinterpret_cast<T*>( rhs )->GetValue( m_lFeature );
    ....
  }
};

然后

typedef CVFunctor<CVChild> ParentToChild;
typedef CVFunctor<CVOtherChild> ParentToOtherChild;
....
ParentToChile p2ch;
bool b = p2ch(SomeParentPtr1, SomeParentPtr2);

您应该重新考虑使用reinterpret_cast。在我看来,在这里检查对dynamic_cast的调用更合适:

T* t = dynamic_cast<T*>( lhs);
if (!t) return false;

最新更新