相关疑难解决方法(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万
查看次数

C++模板覆盖const和非const方法

我有重复相同代码const和非const版本的问题.我可以用一些代码来说明问题.这里有两个样本访问者,一个修改访问对象,另一个不访问.

struct VisitorRead 
{
    template <class T>
    void operator()(T &t) { std::cin >> t; }
};

struct VisitorWrite 
{
    template <class T> 
    void operator()(const T &t) { std::cout << t << "\n"; }
};
Run Code Online (Sandbox Code Playgroud)

现在这里是一个聚合对象 - 这只有两个数据成员,但我的实际代码要复杂得多:

struct Aggregate
{
    int i;
    double d;

    template <class Visitor>
    void operator()(Visitor &v)
    {
        v(i);
        v(d);
    }
    template <class Visitor>
    void operator()(Visitor &v) const
    {
        v(i);
        v(d);
    }
};
Run Code Online (Sandbox Code Playgroud)

并且有一个函数来演示以上内容:

static void test()
{
    Aggregate a;
    a(VisitorRead());
    const Aggregate …
Run Code Online (Sandbox Code Playgroud)

c++ templates visitor

16
推荐指数
2
解决办法
9658
查看次数

标签 统计

c++ ×2

c++-faq ×1

class ×1

code-duplication ×1

const ×1

templates ×1

visitor ×1