프로그래밍 언어/C++

C++ 캐스팅 static_cast / reinterpret_cast 예제

ShovelingLife 2022. 6. 10. 10:31
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <functional>
 
using namespace std;
 
template<typename T, typename F = void*>
T* Cast(F* _ptr)
{
    static_assert(std::is_pointer<F>::value, "포인터가 아님");
    void* p_void   = _ptr;
    T*    p_casted = static_cast<T*>(p_void);
 
    if (!p_casted)
        p_casted = reinterpret_cast<T*>(p_void);
 
    return p_casted;
}
 
class A
{
protected:
    int val = 10;
 
public:
    A()
    {
        cout << "생성자 호출" << endl;
    }
 
    ~A()
    {
        cout << "소멸자 호출" << endl;
    }
 
public:
    void Set(int _val) { val = _val; }
};
 
class B : public A
{
public:
    void Print()
    {
        cout << val << endl;
    }
};
 
int main()
{
    // Heap 메모리에 동적 할당 삭제 필수
    A* p_a = new A();
 
    // 스코프 벗어나면 자동소멸 Stack 메모리
    if (auto p_b = Cast<B>(p_a))
    {
        p_b->Print();
        p_b->Set(20);
        p_b->Print();
    }
    delete p_a;
    // p_a = nullptr; 자유
 
    int* p_int = new int(65);
    char* p_ch = Cast<char>(p_int);
 
    cout << "p_int 값 : " << *p_int << " p_ch 값 : " << (char)*p_ch << endl;
 
    delete p_int;
    return 0;
}