[모던C++입문] 4.3 메타 프로그래밍

    4.3 메타 프로그래밍

    한계

    • 헤더를 포함해야함
    • 내장 타입별 정보를 전달하는 클래스 템플릿 numeric_limits
    template<typename T>
    inline void test(const T& x)
    {
        cout << "x = " << x << " (";
        int oldp = cout.precision(numeric_limits<T>::digits10 + 1);
        cout << x << ")" << endl;
        cout.precision(oldp);
    }
    
    int main()
    {
        test(1.f / 3.f);
        test(1. / 3.0);
        test(1. / 3.0l);
    }
    
    //출력결과
    // x = 0.333333 (0.3333333)
    // x = 0.333333 (0.3333333333333333)
    // x = 0.333333 (0.3333333333333333333)
    
    template<typename Container>
    typename Container::valuetype;
    inline minimum(const Container& c)
    {
        using vt = typename Container::valuetype;
        vt min_value = numeric_limits<vt>::max();
        for(const vt& x : c)
            if(x < min_value)
                min_value = x;
    
        return min_value;
    }
    
    template<typename T>
    T squar_root(const T& x)
    {
        const T my_eps = T{2} * x * numeric_limits<T>::epsilon();
        T r = x;
    
        while(abs((r * r) - x) > my_eps)
            r = (r + x / r) / T{2};
    
        return r;
    }

    타입 특성

    • <type_traits> 은 c++11에 표준화 되었다.
    • is_pod는 타입이 POD(Plain Old Data)타입인지 확인할수 있음
    • POD타입은 c프로그램에서 사용할수 있는 모든 내장 타입(intrinsic type)과 단순 클래스
    • struct여야 하고 메서드가 없거나 조건부 컴파일 되어야한다
    //POD클래스
    struct simple_point
    {
    #ifdef __cplusplus
        simple_point(double x, double y) : x(x), y(y) {}
        simple_point() = default;
        simple_point(initializer_list<double> il)
        {
            auto it = begin(il)
            x = *it;
            y = *next(it)
        }
    #endif
        double x, y;
    }
    반응형

    댓글

    Designed by JB FACTORY