반응형

함수의 리턴타입, 인자타입 정보를 구하는 traits 만들기

  • 메인 템플릿(Main template)을 만들고 typedef T type 제공(C++11 using 동일)

  • 부분 특수화(Partial specialization)를 통한 원하는 타입을 얻을 수 있도록 T 타입 분할

    • 함수 타입 T(double(short, int))를 리턴타입 double과 인자타입(short, int)로 분리

    • T(double(short, int)) -> R(A1, A2)

  • 메인 템플릿의 활용도가 없을 경우 내부 type은 제거 해도 됨

#include <iostream>
using namespace std;

double hoo(short a, int b) { return 0; }

// 반환 타입에 대한 메인 템플릿
template<typename T> 
struct result_type
{
    typedef T type;
};

// 함수타입에 대한 부분 특수화
template<typename T, typename A1, typename A2> 
struct result_type<T(A1, A2)>
{
    typedef T type;
};

// 인자는 복수개이므로 N 파라미터 추가로 필요
template<typename T, size_t N>
struct argument_type
{
    typedef T type;
};

// 첫번째 인자에 대한 부분 특수화
template<typename R, typename A1, typename A2>
struct argument_type<R(A1, A2), 0>
{
    typedef A1 type;
};

// 두번째 인자에 대한 부분 특수화
template<typename R, typename A1, typename A2>
struct argument_type<R(A1, A2), 1>
{
    typedef A2 type;
};

template<typename T> void foo(T& t)
{
    // T : double(short, int)
    typename result_type<T>::type ret_type;
    typename argument_type<T, 0>::type arg_type0;
    typename argument_type<T, 1>::type arg_type1;

    cout << typeid(ret_type).name() << endl; // double
    cout << typeid(arg_type0).name() << endl; // short
    cout << typeid(arg_type1).name() << endl; // int
}
int main()
{
    foo(hoo);
}

C++11 표준의 함수 리턴 타입 구하기

  • result_of(C++17 미만)
  • invoke_result(C++17 이상)
  • decltype 사용해서 구현(일반함수, 함수 객체, 람다표현식등의 모든 callable object 고려)

 

반응형

반응형

type traits 기능(C++11)

  • type에 대한 query : is_pointer<>, is_array<>, extent<>

  • type에 대한 변형 타입 : remove_pointer<>, add_pointer<>

#include <iostream>
#include <type_traits>
using namespace std;

template<typename T> void foo(T a)
{
    bool b = is_pointer<T>::value;
    typename remove_pointer<T>::type t;
    
    cout << typeid(t).name() << endl;
}

int main()
{
    int n = 10;
    foo(n);
    foo(&n);
}

 

remove_pointer 구현 예제

  • remove_pointer_custom 메인 템플릿 생성

    • int -> int 반환

  • remove_pointer_custom 부분 특수화(Partial specialization) 생성

    • int* -> int 반환

#include <iostream>
using namespace std;

// Main template
template<typename T> 
struct remove_pointer_custom
{
    typedef T type;
};

// Partial specialization
template<typename T> 
struct remove_pointer_custom<T*>
{
    typedef T type;
};

template<typename T> void foo(T a)
{
    // 값이 아닌 타입을 꺼낼때는 typename을 꼭 사용 필요
    typename remove_pointer_custom<T>::type t;

    cout << typeid(t).name() << endl;
}

int main()
{
    int n = 10;
    foo(&n);
}

 

remove_all_pointer 구현 예제

  • 중첩 포인터까지 모두 제거 되는 remove_pointer 구하는 방법
#include <iostream>
using namespace std;

template<typename T> 
struct remove_all_pointer_custom
{
    typedef T type;
};

template<typename T> 
struct remove_all_pointer_custom<T*>
{
    // 포인터 타입일때까지 포인터를 제거하며 자기 자신을 호출하고 최종 메인 템플릿이 호출됨
    typedef typename remove_all_pointer_custom<T>::type type;
};

int main()
{
    typename remove_all_pointer_custom<int**>::type n;
    cout << typeid(n).name() << endl;
}
반응형

반응형

integral_constant

  • 컴파일 타임에 결정된 상수 값을 별도 타입화 하여 함수 오버로딩을 할 수 있도록 만드는 int2type 기술
  • int2type 기술을 C++11에서 표준화한 integral_constant

기본 함수 오버로딩(Function overloading)

  • 이자의 개수가 다르거나 인자 타입이 다르면 아래와 같이 인수에 따라 서로 다른 함수가 호출 되게 할 수 있음

  • 인자가 개수가 같고 인자의 타입도 같을때 다른 함수가 되게 하려면?

#include <iostream>
using namespace std;

void foo(int n) {}
void foo(double d) {}

int main()
{
    foo(1); // foo(int)
    foo(1.2); // foo(double)
}

int2type

  • 컴파일 타임 정수형 상수를 각각의 독립된 타입으로 만드는 기술
  • int2type을 사용하면 컴파일 타임에 결정된 정수형 상수를 모두 다른 타입으로 만들 수 있음
    • 1, 2는 같은 타입이지만, int2type<1>, int2type<2>는 다른 타입
  • int2type을 함수 오버로딩에 사용하거나 템플릿 인자, 상속등에 사용할 수 있음
#include <iostream>
using namespace std;

// 같은 정수형 타입이지만 값에 따라 별도의 타입으로 생성
template<int N> struct int2type
{
    static constexpr int value = N;
};

int main()
{
    int2type<1> t0; // int2type<1> 타입
    int2type<2> t1; // int2type<2> 타입
}

int2type 예제

  • printv 함수에서 받은 값의 포인터 타입 여부에 따라 분기처리 코드가 작성되어 값과 포인터 참조값을 출력하도록 되어 있음

  • 포인터 여부는 컴파일 타임에 체크되지만 if 구문이 런타임 조건문으로 하위 코드들은 모두 컴파일 대상

  • 포인터가 아닌 값에 대해서는 사용할 수 없는 구분이 포함되어 간접 참조 에러가 발생함

  • 간접 참조 에러가 발생하는 구문을 별도의 함수 템플릿으로 분리함

  • 각 함수 템플릿은 int2type을 활용하여 인자 타입으로 구분하여 사용

  • 동일 이름을 가지는 함수가 여러개 있을때, 어느 함수를 호출할지는 컴파일 타임에 결정됨

  • 호출이 결정되지 않은 템플릿은 instantiation 되지 않음

#include <iostream>
using namespace std;

// 포인터 타입 체크용 메인 템플릿
template<typename T> struct is_pointer_custom
{
    //enum { value = false }; 
    static constexpr bool value = false; // c++11
};

// 포인터 타입에 대해서 부분 특수화 필요
template<typename T> struct is_pointer_custom<T*>
{
    //enum { value = true };
    static constexpr bool value = true; // c++
};
...

// 같은 정수형 타입이지만 값에 따라 별도의 타입으로 생성되는 타입 도구
template<int N> struct int2type
{
    static constexpr int value = N;
};

// 컴파일 타임 상수 값 구분용 함수 템플릿
template<typename T>
void printv_imp(T v, int2type<1>)
{
    cout << v << " : " << *v << endl;
}

// 컴파일 타임 상수 값 구분용 함수 템플릿
template<typename T>
void printv_imp(T v, int2type<0>)
{
    cout << v << endl;
}

// 값을 받아서 출력하고, 포인터일 경우 포인터의 값까지 출력
template<typename T> void printv(T v)
{
    // 아래의 조건으로 분기 코드 작성시 if 구문이 런타임 조건문으로
    // 포인터가 아닌 값에 대해서 컴파일 에러 발생
    //if(is_pointer_custom<T>::value)
    //    cout << v << " : " << *v << endl;
    //else
    //    cout << v << endl;

    // 출력 구현부를 별도로 분리하여 함수 템플릿으로 타입을 구분하여 문제 해결 가능
    printv_imp(v, int2type<is_pointer_custom<T>::value>());
    // is_pointer_custom 반환 값에 의해(포인터: int2type<1>, 포인터 아님: int2type<0> 타입)
}

int main()
{
    int n = 3;
    printv(n);
    printv(&n);
}

 

integral_constant 예제

  • int뿐 아니라 모든 정수 계열 상수 값을 타입으로 만들 수 있게 하는 템플릿(실수는 템플릿 인자 사용X)

    • bool, char, short, int, long, long long
  • true_type, false_type

    • true/false: 참 거짓을 나타내는 값, 서로 같은 타입

    • true_type/false_type: 참 거짓을 나타내는 값, 서로 다른 타입

  • is_pointer등의 type_traits를 만들때 intergral_constant를 기반 클래스로 사용하여 간소화 및 가독성을 높일 수 있음
    • T가 포인터가 아니라면, value = false, 기반 클래스는 false_type
    • T가 포인터라면, value = true, 기반 클래스는 true_type
#include <iostream>
using namespace std;

template<typename T, T N> 
struct integral_constant
{
    static constexpr T value = N;
};

// int 타입 0, 1 서로 다른 타입
integral_constant<int, 0> t0;
integral_constant<int, 1> t1;

// short 타입, 0, 1 서로 다른 타입
integral_constant<short, 0> s0;
integral_constant<short, 1> s1;

// bool 타입, true, false 서로 다른 타입
integral_constant<bool, true> tb1;
integral_constant<bool, false> tb0;

// bool 타입은 활용 빈도가 높으므로 true_type, false_type 별칭 만들어서 사용
typedef integral_constant<bool, true> true_type;
typedef integral_constant<bool, false> false_type;

template<typename T>
struct is_pointer : false_type
{
    // false_type 상속으로 아래 코드 생략
    //static constexpr bool value = false;
};

template<typename T>
struct is_pointer<T*> : true_type
{
    // true_type 상속으로 아래 코드 생략
    //static constexpr bool value = true;
};

 

C++11 type_traits 활용하여 int2type 예제 간소화

  • C++11 <type_traits>헤더 포함

  • int2type<0>, int2type<1> -> integral_constant<0>, integral_constant<1>

  • integral_constant<0>, integral_constant<1> -> false_type, true_type

#include <iostream>
#include <type_traits>
using namespace std;

// 컴파일 타임 상수 값 구분용 함수 템플릿
template<typename T>
void printv_imp(T v, true_type)
{
    cout << v << " : " << *v << endl;
}

// 컴파일 타임 상수 값 구분용 함수 템플릿
template<typename T>
void printv_imp(T v, false_type)
{
    cout << v << endl;
}

// 값을 받아서 출력하고, 포인터일 경우 포인터의 값까지 출력
template<typename T> void printv(T v)
{
    printv_imp(v, is_pointer<T>());
}

int main()
{
    int n = 3;
    printv(n);
    printv(&n);
}

 

C++17 if constexpr를 사용하여 컴파일 타임에 분기처리 가능

#include <iostream>
#include <type_traits>
using namespace std;

// 값을 받아서 출력하고, 포인터일 경우 포인터의 값까지 출력
template<typename T> void printv(T v)
{
    if constexpr(is_pointer<T>::value)
        cout << v << " : " << *v << endl;
    else
        cout << v << endl;
}

int main()
{
    int n = 3;
    printv(n);
    printv(&n);
}
반응형

반응형

is_array 예제

  • 간단히 템플릿 파라미터 T가 배열 타입 여부 확인 도구

  • 메인 템플릿(Main template)에서 false 반환( value = false )

  • 배열 타입 부분 특수화(Partial specialization)에서 true 반환( value = true )

  • 타입을 정확히 알아야 함

    • int x[3]; 에서 x는 변수 이름, 변수 이름을 제외한 나머지 요소(int[3])이 타입임

  • unknown size array type(T[])에 대해서도 부분 특수화가 필요함

#include <iostream>
#include <type_traits>
using namespace std;

template<typename T> struct is_array_custom
{
    static constexpr bool value = false;
};

// 크기를 알 수 있는 배열의 부분 특수화
template<typename T, size_t N>
struct is_array_custom<T[N]>
{
    static constexpr bool value = true;
};

// 크기를 알 수 없는 배열의 부분 특수화
template<typename T, size_t N>
struct is_array_custom<T[N]>
{
    static constexpr bool value = true;
};

template<typename T> void foo(T& a)
{
    // 크기를 알 수 있는 배열 확인
    if (is_array_custom<T>::value)
        cout << "array" << endl;
    else
        cout << "not array" << endl;
      
    // 크기를 알 수 없는 배열을 사용하는 패턴도 존재함
    //if (is_array_custom<int[]>::value)
}

int main()
{
    int x[3] = { 1, 2, 3 };
    foo(x);
}

 

is_array 배열 크기 구하기

  • 부분 특수화로 배열의 크기도 구할 수 있음

    • c++11 extent<T, 0>::value 존재

#include <iostream>
#include <type_traits>
using namespace std;

template<typename T> struct is_array_custom
{
    static constexpr bool value = false;
    static constexpr size_t size = -1;
};

//사이즈를 알 수 있는 배열에 대한 부분 특수화에서 N이 배열의 크기
template<typename T, size_t N>
struct is_array_custom<T[N]>
{
    static constexpr bool value = true;
    static constexpr size_t size = N;
};

template<typename T> void foo(T& a)
{
    if (is_array_custom<T>::value)
        cout << "size of array : " << is_array_custom<T>::size << endl;
}

int main()
{
    int x[3] = { 1, 2, 3 };
    foo(x);
}
반응형

반응형

type traits 개념

  • 컴파일 타임에 타입에 대한 정보를 얻거나 변형된 타입을 얻을때 사용하는 도구(메타 함수)

  • <type_traits> 헤더로 제공됨(c++11)

type query를 위한 type traits 만드는 방법

  • 메인 템플릿(Primary template)에서 false 반환( value = false )

  • 부분 특수화(Partial specialization)에서 true 반환( value = true )

 

is_pointer 예제

  • 간단히 템플릿 파라미터 T가 포인터 타입 여부 확인 도구

  • 메인 템플릿(Primary template)에서 false 반환( value = false )
  • 포인터 타입용 부분 특수화(Partial specialization)에서 true 반환( value = true )
#include <iostream>
#include <type_traits>
using namespace std;

template<typename T> struct is_pointer_custom
{
    enum { value = false }; 
};

// 포인터 타입에 대해서 부분 특수화 필요
template<typename T> struct is_pointer_custom<T*>
{
    enum { value = true };
};

template<typename T> void foo(T v)
{
    if (is_pointer_custom<T>::value)
        cout << "pointer" << endl;
    else
        cout << "not pointer" << endl;
}

int main()
{
    int n = 3;
    foo(n);
    foo(&n);
}

 

is_pointer 개선 예제

  • c++11 기준 코드 개선
  • 좀더 다양한 포인터 타입 지원(const, volatile, const volatile)
#include <iostream>
#include <type_traits>
using namespace std;

template<typename T> struct is_pointer_custom
{
    //enum { value = false }; 
    static constexpr bool value = false; // c++11
};

// 포인터 타입에 대해서 부분 특수화 필요
template<typename T> struct is_pointer_custom<T*>
{
    //enum { value = true };
    static constexpr bool value = true; // c++
};

// 포인터 타입에 대해서 부분 특수화 필요
template<typename T> struct is_pointer_custom<T* const>
{
    //enum { value = true };
    static constexpr bool value = true; // c++
};

// 포인터 타입에 대해서 부분 특수화 필요
template<typename T> struct is_pointer_custom<T* volatile>
{
    //enum { value = true };
    static constexpr bool value = true; // c++
};

// 포인터 타입에 대해서 부분 특수화 필요
template<typename T> struct is_pointer_custom<T* const volatile>
{
    //enum { value = true };
    static constexpr bool value = true; // c++
};

int main()
{
    cout << is_pointer_custom<int>::value << endl;
    cout << is_pointer_custom<int*>::value << endl;
    cout << is_pointer_custom<int* const>::value << endl;
    cout << is_pointer_custom<int* volatile>::value << endl;
    cout << is_pointer_custom<int* const volatile>::value << endl;
    cout << is_pointer_custom<int* volatile const>::value << endl;
}
반응형

반응형

constexpr 함수

  • 함수앞에 constexpr 붙이면 파라미터가 컴파일 타임 상수 일 경우 함수를 컴파일 시간에 연산(성능 이점)

  • 일반 변수 파라미터 입력시 일반 함수처럼 동작

#include <iostream>
#include <type_traits>
using namespace std;

template<int N> struct Check
{

};

// constexpr 함수(c++11)
constexpr int add(int a, int b)
{
    return a + b;
}

int main()
{
    int n1 = 1, n2 = 2;

    int n = add(n1, n2);   // OK(일반 변수 파라미터 입력 시 일반 함수처럼 동작)
    int m = add(1, 2);     // OK(컴파일 타임 상수 파라미터 입력 시 컴파일 타임에 연산)
    Check<add(1, 2)> c;    // OK(컴파일 타임에 연산됨으로 템플릿 파라미터로 사용 가능)
    Check<add(n1, n2)> c2; // Error(일반 함수처럼 동작하므로 템플릿 파라미터로 사용 불가)
}
반응형

반응형

템플릿 메타 프로그래밍

  • 컴파일 시간에 연산을 수행하는 개념
  • 템플릿 파라미터 5를 받았을때 5 * 4 * 3 * 2 * 1 값을 반환하는 Factorial 구현
#include <iostream>
#include <type_traits>
using namespace std;

//  템플릿 메타 프로그래밍(template meta programming)
template<int N> struct Factorial
{
    enum { value = N * Factorial<N-1>::value };
};

// 재귀의 종료를 위해 특수화(Specialization)
template<> struct Factorial<1>
{
    enum { value = 1 };
};

int main()
{

    int n = Factorial<5>::value; // 5 * 4 * 3 * 2 * 1 => 120
    // 5 * Factorial<4>::value
    // 4 * Factorial<3>::value
    // 3 * Factorial<2>::value
    // 2 * Factorial<1>::value
    // 1

    cout << n << endl;
}

 

C++11 이후 부터는 enum대신 constexpr을 사용할 수 있다.

#include <iostream>
#include <type_traits>
using namespace std;

//  템플릿 메타 프로그래밍(template meta programming)
template<int N> struct Factorial
{
    //enum { value = N * Factorial<N-1>::value };
    static constexpr int value = N * Factorial<N - 1>::value;
};

// 재귀의 종료를 위해 특수화(Specialization)
template<> struct Factorial<1>
{
    //enum { value = 1 };
    static constexpr int value = 1;
};

int main()
{

    int n = Factorial<5>::value; // 5 * 4 * 3 * 2 * 1 => 120
    // 5 * Factorial<4>::value
    // 4 * Factorial<3>::value
    // 3 * Factorial<2>::value
    // 2 * Factorial<1>::value
    // 1

    cout << n << endl;
}
반응형

반응형

XTuple(Couple 선형화 구현)

  • Couple 재귀 호출 대신 선형 호출 할 수 있는 패턴 지원
    • Couple<int, Couple<int, double>...> -> XTuple<int, int, double...> 형태로 개선
  • Null 클래스 활용(Empty class)

    • 멤버 없는 클래스

    • 크기는 항상 1(sizeof(Null))

    • 멤버는 없지만 타입이므로 함수 오버로딩이나 템플릿 인자로 활용

  • 상속 활용 기술

  • 개수의 제한을 없앨 수 없을까? C+++ Variadic template

#include <iostream>
#include <type_traits>
using namespace std;

template<typename T, typename U> struct Couple
{
    T v1;
    U v2;

    enum { N = 2 };
};

// 빈 파라미터로 활용하기 위한 empty class
struct Null {};

// 2개이상 5개 미만의 타입전달
template<typename P1,
typename P2,
typename P3 = Null,
typename P4 = Null,
typename P5 = Null> 
class XTuple 
    : public Couple<P1, XTuple<P2, P3, P4, P5, Null>>
{

};

// XTuple 상속을 종료하기 위한 특수화
template<typename P1, typename P2>
class XTuple<P1, P2, Null, Null, Null>
    : public Couple<P1, P2>
{

};

int main()
{
    // Couple을 선형화하여 XTuple 형태로 사용
    XTuple<int, char, long, short, double> t5;
}
반응형

+ Recent posts