Avoiding const_cast when calling std::set::find

后端 未结 3 1594
心在旅途
心在旅途 2021-01-11 18:23

Is there any good way to obviate the const_cast below, while keeping const correctness?

Without const_cast the code below doesn\'t compile.

相关标签:
3条回答
  • 2021-01-11 19:24

    Yes.

    In C++14, you can use your own comparator that declares int const* as transparent. This would enable the template overload of find() that can compare keys against arbitrary types. See this related SO question. And here's Jonathan Wakely's explanation.

    0 讨论(0)
  • 2021-01-11 19:29

    I want to explain the underlying logic of why this is impossible.

    Suppose set<int*>::find(const int*) would be legitimate. Then you could do the following:

    set<int*> s;
    const int* p_const;
    // fill s and p
    auto it = s.find(p_const);
    int* p = *it;
    

    Hey presto! You transformed const int* to int* without performing const_cast.

    0 讨论(0)
  • 2021-01-11 19:30

    Is there any good way to obviate the const_cast below, while keeping const correctness?

    I am not sure whether what I am going to suggest qualifies as a "good way". However, you can avoid the const_cast if you don't mind iterating over the contents of the set yourself. Keep in mind that this transforms what could be an O(log(N)) operation to an O(N) operation.

    bool isPtrInSet(const int* ptr) const
    {
       for ( auto p : m_set )
       {
          if ( p == ptr )
          {
             return true;
          }
       }
       return false;
    }
    
    0 讨论(0)
提交回复
热议问题