2016-11-16 15 views
0

answer을보고 사용하고 싶습니다. 그러나, static_castconst_cast을 사용할 때 세분화 오류가 발생하지만 임시 변수를 사용하면 문제가 없습니다. 그것은 분명히 bar()의 non-const 버전이 자체 over-and-over라고 부르기 때문입니다. 하지만 static_castconst foo*이되고 bar()의 const 버전을 선택합니다. 왜 이렇게이다?const_cast (또는 static_cast)가 const를 추가하지 않는 이유는 무엇입니까?

#include <iostream> 
using namespace std; 

class foo 
{ 
    public: 
    void bar() const 
    { 
     cout << "const" << endl; 
    } 

    void bar() 
    { 
     cout << "non-const" << endl; 

//  static_cast<const decltype(this)>(this)->bar(); 

//  const_cast<const decltype(this)>(this)->bar(); 

     const auto& tmp = *this; 
     tmp.bar(); 
    } 
}; 

int main() { 
    foo A; 
    A.bar(); 
    const foo B; 
    B.bar(); 
    static_cast<const foo*>(&A)->bar(); 
    return 0; 
} 
+0

@songyuanyao, 주석 처리 된 행을 제거하십시오. 영원히 되풀이됩니다. – StoryTeller

+1

'this'는 포인터이므로,'foo *'타입을가집니다. const를'foo *'에 추가하면 예상대로'foo const *'가 아닌'foo * const'가됩니다. – ach

답변

5

decltype(this)foo*입니다. const decltype(this)foo* const입니다.

당신은 pointees cv-qualifications를 변경하지 않고 포인터 만 변경합니다. 따라서 매번 non-const 과부하가 선택됩니다.

+1

좋습니다. 실제로 이해가됩니다. 나는 그것을 참조로 던지면 똑같은 일이 일어난다 고 생각한다.'const foo &'대신'foo & const' (말도 안되는 것)가 될 것이다. – Jonas

+1

대신에 할 수있는 일을 암시하지만, 명시 적으로 언급하는 것이 유용 할 수 있습니다 :'static_cast *> (this)'가 작동해야합니다. 그것은 길지만, OP가 피하려고 생각했던 것을 피할 수 있습니다. 즉, 형식을 명시 적으로 지정하지 않아도됩니다. – hvd

+1

@hvd, meta_function이 [this] (http://ideone.com/RPGzLf)와 같이 정의되어있는 경우 static_cast :: type> (this)'을 사용할 수도 있습니다. 철저하게 테스트하지 않았습니다. – StoryTeller