C++ template to cover const and non-const method

后端 未结 7 1508
北荒
北荒 2020-12-29 22:48

I have a problem with duplication of identical code for const and non-const versions. I can illustrate the problem with some code. Here are two s

7条回答
  •  猫巷女王i
    2020-12-29 23:20

    struct Aggregate
    {
        int i;
        double d;
    
        template 
        void operator()(Visitor &v)
        {
            visit(this, v);
        }
        template 
        void operator()(Visitor &v) const
        {
            visit(this, v);
        }
      private:
        template
        static void visit(ThisType *self, Visitor &v) {
            v(self->i);
            v(self->d);
        }
    };
    

    OK, so there's still some boilerplate, but no duplication of the code that depends on the actual members of the Aggregate. And unlike the const_cast approach advocated by (e.g.) Scott Meyers to avoid duplication in getters, the compiler will ensure the const-correctness of both public functions.

提交回复
热议问题