Const函数调用非常量,反之亦然(避免重复)? [英] Const function calling non const or vice versa (to avoid duplication)?

查看:121
本文介绍了Const函数调用非常量,反之亦然(避免重复)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class Foo 
{
public:
const int& get()const
{
//这里的东西
return myInt;
}

int& get()
{
return const_cast< int&>(static_cast< const Foo *>(this) - > get());
}
};



  class Foo 
{
public:
int& get()
{
//这里的东西
返回myInt;
}

const int& get()const
{
return const_cast< Foo *>(this) - > get();
}
};

我只使用第一个,但我只是看到第二个使用的地方,所以我想知道。

注释 //这里的东西可能是一个非平凡的检查,例如检索表中的索引为了返回一个表格成员的ref(例如: myInt = myTable [myComputedIndex]; ),所以我不能将它公开。因此,表和任何成员不是常量。

解决方案

如果你必须做一个const不可知的函数,并避免重复,一个简单的方法就是将实现委托给一个模板,例如

  class Foo {
private:

int my_int;
模板< typename ThisPtr>
static auto& get(ThisPtr this_ptr){
return this_ptr-> my_int;
}

public:
int& get(){
return get(this);
}

const int& get()const {
return get(this);
}
};

这样您就可以免于使用 const_cast mutable 以及其他在这种情况下试图减少代码重复的东西。如果你出错了,编译器会让你知道。

Is there any advantage using one over the other:

class Foo
{
public:
    const int& get() const
    {
        // stuff here
        return myInt;
    }

    int& get()
    {
        return const_cast<int&>(static_cast<const Foo*>(this)->get());
    }
};

Or

class Foo
{
public:
    int& get()
    {
        // stuff here
        return myInt;
    }

    const int& get() const
    {
        return const_cast<Foo*>(this)->get();
    }
};

I only used the first one, but I just saw the second one used somewhere, so I am wondering.

The comment // stuff here could be a non-trivial check like retrieving the index of a table in order to return a ref on a member of the table (for example: myInt = myTable[myComputedIndex];) so I cannot just make it public. Thus table and any member are not const.

解决方案

If you have to make a function that is const-agnostic, and avoids duplication, one neat way to do it is delegating implementation to a template, for example

class Foo {
private: 

    int my_int;
    template <typename ThisPtr>
    static auto& get(ThisPtr this_ptr) { 
        return this_ptr->my_int;
    }

public:
    int& get() {
        return get(this);
    }

    const int& get() const {
        return get(this);
    }
};

This way you are free from the fear associated with using const_cast, mutable and other stuff that goes into trying to reduce code duplication in cases like this. If you get something wrong, the compiler will let you know.

这篇关于Const函数调用非常量,反之亦然(避免重复)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆