How to generate a non-const method from a const method?

后端 未结 11 2444
时光取名叫无心
时光取名叫无心 2021-02-08 11:18

While striving for const-correctness, I often find myself writing code such as this

class Bar;

class Foo {
public:
  const Bar* bar() const { /* code that gets          


        
11条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-08 11:28

    One picture worth more than 10 thousand words, so:

    const Item*
    Storage::SearchItemBySomething( const Something &something ) const
    {
        const Item* pData = NULL;
    
        // Algorythm for searching.
    
        return pData;
    }
    
    Item*
    Storage::SearchItemBySomething( const Something &something )
    {
        return (Item*) ((const Storage*)this)->_SearchItemBySomething(something);
    }
    

    Copied and altered from actual code. General idea is that you implement your const method and you write the non const method which uses the first. You need to cast the "this" pointer to "const" and you need to cast away the "const" from the returning "const Item*".

    You can replace the C-style casts to C++ style casts

    • static_cast( ... )
    • const_cast(this)

提交回复
热议问题