【问题标题】:Operator overloading and type casting运算符重载和类型转换
【发布时间】:2013-11-21 10:23:57
【问题描述】:

假设我们的类名 Default 有两个属性 x 和 y。
比较对象的默认操作是使用属性 x。

当我们想使用其他属性 y 比较这个对象时,
1.创建可以通过使用属性 y 进行比较的新派生类是否安全,然后将指针从 Default 转换为该新类并比较对象?
2. 在不降低操作性能的情况下,有什么替代方法可以做到这一点?

要求是我们不能更改排序算法的签名以将函数指针传递给差异比较器。

顺便说一下,这种方法不需要转换或复制数据。

class Default {public:int x; int y;};

class Compare1 : public Default {};

bool operator < (const Default  &left,const Default &right)
{
    return left.x < right.x;
}
bool operator < (const Compare1  &left,const Compare1 &right)
{
    return left.y < right.y;
}

template<typename T>
int *sort_element(const T *data, int size)
{
    int *permute;
    //... do some sorting by using < comparator ...
    return permute;
}

int main(){
    Default *obj;
    int obj_size;
    //… initialize obj and obj size..

    // sorting object with default order.
    int *output_default = sort_element(obj, obj_size)

    // sorting with customize comparator.
    Compare1 *custom1 = static_cast<Compare1*>(obj);
    int *output_custom1 = sort_element(custom1, obj_size);
}

【问题讨论】:

    标签: c++ types casting operators overloading


    【解决方案1】:

    在对它们进行排序时,最好将仿函数或 lambda 作为比较函数传递。您的排序函数必须接受一个函数:

    template<typename T, typename F>
    int *sort_element(const T *data, int size, F comp)
    {
    
        ....
    
        if (comp(a, b))
           ....
    
        ...
    }
    

    然后

    // Sort by x
    sort_element(..., [](const Default &a, const Default &b) {
          return a.x < b.x;
      });
    
    // Sort by y
    sort_element(..., [](const Default &a, const Default &b) {
          return a.y < b.y;
      });
    

    如果你没有 C++11,你可以使用函数对象(functor)来代替:

    struct fx
    {
        bool operator()(const Default &a, const Default &b) const
        {
            return a.x < b.x;
        }
    };
    
    struct fy
    {
        bool operator()(const Default &a, const Default &b) const
        {
            return a.y < b.y;
        }
    };
    
    // Sort by x
    sort_element(..., fx());
    
    // Sort by x
    sort_element(..., fy());
    

    忘记你的第二课 Compare1 并删除它。

    【讨论】:

    • 听起来不错,但有一种情况是我无法更改函数 sort_element 的标题。
    • 如果你不能那么不幸你别无选择,你的代码是唯一的选择,那么你应该停止担心效率。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    相关资源
    最近更新 更多