How do I remove code duplication between similar const and non-const member functions?

后端 未结 19 1988
天涯浪人
天涯浪人 2020-11-22 00:30

Let\'s say I have the following class X where I want to return access to an internal member:

class Z
{
    // details
};

class X
{
    std::vec         


        
19条回答
  •  孤城傲影
    2020-11-22 01:08

    This DDJ article shows a way using template specialization that doesn't require you to use const_cast. For such a simple function it really isn't needed though.

    boost::any_cast (at one point, it doesn't any more) uses a const_cast from the const version calling the non-const version to avoid duplication. You can't impose const semantics on the non-const version though so you have to be very careful with that.

    In the end some code duplication is okay as long as the two snippets are directly on top of each other.

提交回复
热议问题