C-style 캐스트 (C-style cast):

  1. (type)value와 같이 사용합니다.

static_cast:

  1. 컴파일 시간에 검사되는 일반적인 캐스트입니다.

    #include <iostream>
    
    int main() {
        int a = 10;
        double b = static_cast<double>(a);
    
        std::cout << "static_cast: " << b << std::endl;
    
        return 0;
    }
    

dynamic_cast:

  1. 런타임에 타입 정보를 사용하여 안전하게 다운캐스팅을 수행합니다.

    #include <iostream>
    
    class Base {
    public:
        virtual void foo() {}
    };
    
    class Derived : public Base {};
    
    int main() {
    //업 캐스팅
        Base* basePtr = new Derived;
    //다운 캐스팅
        Derived* derivedPtr = dynamic_cast<Derived*>(basePtr);
    
        if (derivedPtr) {
            std::cout << "dynamic_cast successful." << std::endl;
        } else {
            std::cout << "dynamic_cast failed." << std::endl;
        }
    
        delete basePtr;
    
        return 0;
    }
    

const_cast:

  1. const를 추가하거나 제거하는데 사용됩니다.

    #include <iostream>
    
    int main() {
        const int x = 5;
        int y = const_cast<int&>(x);
    
        std::cout << "const_cast: " << y << std::endl;
    
        return 0;
    }
    

reinterpret_cast:

  1. 매우 강력한 캐스트로, 서로 다른 형식 간의 포인터나 참조를 변환할 때 사용됩니다.

    #include <iostream>
    
    int main() {
        int* ptr = new int(42);
        long long int ptrValue = reinterpret_cast<long long int>(ptr);
    
        std::cout << "reinterpret_cast: " << ptrValue << std::endl;
    
        delete ptr;
    
        return 0;
    }
    

auto 형식 추론:

  1. C++11 이후 도입된 형식 추론 기능으로, 변수 선언 시 자동으로 형식을 추론합니다.

    #include <iostream>
    
    int main() {
        auto x = 3.14;
    
        std::cout << "auto: " << x << std::endl;
    
        return 0;
    }
    

decltype 형식 추론:

  1. 주어진 표현식의 형식을 추론합니다.

    #include <iostream>
    
    int main() {
        int a = 5;
        double b = 3.14;
    
        decltype(a + b) result = a + b;
    
        std::cout << "decltype: " << result << std::endl;
    
        return 0;
    }