从返回迭代器的const和非const方法中删除代码重复 [英] Removing code duplication from const and non-const methods that return iterators

查看:168
本文介绍了从返回迭代器的const和非const方法中删除代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑这个问题上const和非const类方法。首选的答案取自Scott Meyers的Effective C ++,其中非const方法是用const方法实现的。

I'm considering this question on const and non-const class methods. The preferred answer is taken from Effective C++ by Scott Meyers, where the non-const method is implemented in terms of the const method.

进一步扩展,如果方法返回迭代器而不是引用,如何减少代码重复?修改关联问题中的示例:

Extending this further, how can code duplication be reduced if the methods return iterators instead of references? Modifying the example in the linked question:

class X
{
    std::vector<Z> vecZ;    
public:
    std::vector<Z>::iterator Z(size_t index)
    {
        // ...
    }
    std::vector<Z>::const_iterator Z(size_t index) const
    {
        // ...
    }
};

我不能用const方法实现非const方法,因为它不可能

I can't implement the non-const method in terms of the const method because it's not possible to convert directly from a const_iterator to an iterator without using the distance()/advance() technique.

在示例中,因为我们使用std :: vector作为一个const容器,它实际上可能从一个const_iterator转换到一个迭代器,因为它们可能被实现为指针。我不想依靠这个。是否有更通用的解决方案?

In the example, because we're using a std::vector as the container, it might actually be possible to cast from a const_iterator to an iterator because they may well be implemented as pointers. I don't want to rely on this. Is there a more general solution?

推荐答案

我相信,只有帮助者才能使用

I believe, it is only possible with the helper

typedef int Z;

class X
{
    std::vector<Z> vecZ;    
public:
    std::vector<Z>::iterator foo(size_t index)
    {
        return helper(*this);
    }
    std::vector<Z>::const_iterator foo(size_t index) const
    {
        return helper(*this);
    }

    template <typename T>
    static auto helper(T& t) -> decltype(t.vecZ.begin())
    {
        return t.vecZ.begin();
    }
};

EDIT
同样可以不使用c ++ 11

EDIT Same can be implemented without c++11

template <typename T>
struct select
{
    typedef std::vector<Z>::iterator type;
};
template <typename T>
struct select<const T&>
{
    typedef std::vector<Z>::const_iterator type;
};

template <typename T>
static
typename select<T>::type
helper(T t) 
{
    return t.vecZ.begin();
}

但是,我想你应该三思而后行approcach

But, well, I think you should think twice before using this approcach

这篇关于从返回迭代器的const和非const方法中删除代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆