如何避免语法上相同的const和非const函数之间的代码重复,这些函数在语义上不相同

mkm*_*afa 5 c++

#include <iostream>
using namespace std;

class A 
{
    public:
    A() : x(0) {}
    // notice: not identical to const version but does update
    void FA() {std::cout << "A" << std::endl; x++;}
    void FA() const {std::cout << "const A" << std::endl;}
    private:
    int x;
};

class B
{
    public:
    B() : x(0) {}
    // notice: not identical to const version but does update
    void FB() {std::cout << "B" << std::endl; x++;}
    void FB() const {std::cout << "const B" << std::endl;}
    private:
    int x;
};

class C
{
    public:
    void FC()
    {
        bool condition = true; // should be set to a real condition

        if(condition)
        {
            a.FA();
        }
        b.FB();
    }

    void FC() const
    {
        bool condition = true; // should be set to a real condition

        if(condition)
        {
            a.FA();
        }
        b.FB();
    }

    private:
    A a;
    B b;
};

int main() {
    C c;
    c.FC();

    const C cc;
    cc.FC();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

首先,对于冗长的标题感到抱歉.如何在函数FC,FC const中避免C类中的代码重复?因为你不能用铸造的把戏const的,并要求从非const的FC版本的常量FC版本,因为非const的FC的身体竟然将调用函数,将做一个更新不相同,其相应的常量.

Ral*_*zky 7

让模板成员函数执行实际工作.换句话说:试试这个:

class C
{
public:
    void FC()
    {
        FC_Impl( *this );
    }

    void FC() const
    {
        FC_Impl( *this );
    }

private:
    template <typename Self>
    static void FC_Impl( Self & self )
    {
      bool condition = true; // should be set to a real condition

      if(condition)
      {
          self.a.FA();
      }
      self.b.FB();
    }

    A a;
    B b;
};
Run Code Online (Sandbox Code Playgroud)

  • @RichardHodges静态成员函数是成员函数 (2认同)