1

目前我有一个排序功能:

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) );
4

3 回答 3

2

不可能将任何动态(仅在运行时已知)类型传递给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);
于 2012-09-18T06:02:49.730 回答
1

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

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 );
  ....
}
于 2012-09-18T05:51:34.123 回答
1

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

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;
于 2012-09-18T06:16:50.323 回答