Avoiding const_cast when calling std::set::find

后端 未结 3 1593
心在旅途
心在旅途 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:29

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

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

    set 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.

提交回复
热议问题