본문 바로가기
SWE/C++ OOP

C++ template | type_traits | modern C++ 모르겠음 ㅠㅠ

by S나라라2 2022. 1. 11.
반응형

 

템플릿 클래스 정의

template<typename T>
class A
{
public:
	vector<T> vec;
};

 

템플릿 클래스 사용

A<int> a;

 

 

템플릿 파라미터가 템플릿인지 확인하는 방법

 

#include <type_traits>

template<typename T>
class A
{
public:
	vector<T> vec;	
};


template <class, template <class> class>
struct is_instance : public std::false_type {};

template <class T, template <class> class U>
struct is_instance<U<T>, U> : public std::true_type {};

int mian()
{
	A<int> a;
    std::cout << is_instance<
}

 

 

modern C++ 코드 이해 못하겠어 ㅠㅠ 

#include <iostream>
#include <type_traits>
#include <string>

template <class, template <class> class>
struct is_instance : public std::false_type {};

template <class T, template <class> class U>
struct is_instance<U<T>, U> : public std::true_type {};

template <class>
class Second 
{};

int main()
{
    using A = Second<int>;
    using B = Second<std::string>;
    using C = float;
    std::cout << is_instance<A, Second>{} << '\n'; // prints 1
    std::cout << is_instance<B, Second>{} << '\n'; // prints 1
    std::cout << is_instance<C, Second>{} << '\n'; // prints 0
}

Better make it template <class, template <class...> class> struct is_instance. This way you are not restricted to templates with only one parameter. Also you should note that this only works for templates with typename arguments.

 

 

https://stackoverflow.com/questions/16337610/how-to-know-if-a-type-is-a-specialization-of-stdvector

반응형