相关疑难解决方法(0)

如何删除类似const和非const成员函数之间的代码重复?

假设class X我想要返回内部成员的访问权限:

class Z
{
    // details
};

class X
{
    std::vector<Z> vecZ;

public:
    Z& Z(size_t index)
    {
        // massive amounts of code for validating index

        Z& ret = vecZ[index];

        // even more code for determining that the Z instance
        // at index is *exactly* the right sort of Z (a process
        // which involves calculating leap years in which
        // religious holidays fall on Tuesdays for
        // the next thousand years or so)

        return ret;
    }
    const …
Run Code Online (Sandbox Code Playgroud)

c++ const class code-duplication c++-faq

228
推荐指数
11
解决办法
3万
查看次数

从const和返回迭代器的非const方法中删除代码重复

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

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

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
    {
        // ...
    }
};
Run Code Online (Sandbox Code Playgroud)

我不能在const方法方面实现非const方法,因为不使用distance()/ advance()技术就无法直接从const_iterator转换为迭代器.

在这个例子中,因为我们使用std :: vector作为容器,所以实际上可以从const_iterator转换为迭代器,因为它们很可能被实现为指针.我不想依赖于此.有更通用的解决方案吗?

c++ const dry

9
推荐指数
2
解决办法
1181
查看次数

标签 统计

c++ ×2

const ×2

c++-faq ×1

class ×1

code-duplication ×1

dry ×1