Notice
Recent Posts
Recent Comments
Link
헤더파일
C++17 if 초기화, if constexpr, 구조체 바인딩 본문
int ret = foo();
if (ret == 0)
{
}
// C++17 스타일
// if ( init 구문; 조건문 )
if (int ret = foo(); ret == 0)
{
cout << "ret is 0" << endl;
}
// switch 문에도 초기화 구문을 추가할수 있습니다.
switch (int n = foo(); n)
{
case 0: break;
case 1: break;
}
어떤 함수 foo의 리턴값을 받아 조건문을 구성할 때 이전처럼 다른 줄에 쓰지 않고 조건문의 조건안에 쓸 수 있습니다.
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 = 10;
printv(n);
printv(&n);
}
if문에 constexpr을 붙이지 않으면 컴파일 타임에 오류가 발생합니다. n을 넘겼을 때도 cout << v << " : " << *v << endl; 문에 대한 컴파일 검사가 수행되어 오류가 발생합니다.
constexpr을 붙인다면 조건문이 컴파일타임에 평가 되어 n이 넘어갔을 경우 else 문으로 제어가 넘어가 오류가 발생하지 않게 됩니다.
struct Point
{
int x;
int y;
};
int main()
{
Point pt = { 1,2 };
//int a = pt.x;
//int b = pt.y;
auto [a, b] = pt;
auto& [rx, ry] = pt;
int x[2] = { 1,2 };
auto[e1, e2] = x;
pair<int, double> p(1, 3.4);
auto[n, d] = p;
tuple<int, short, double> t3(1, 2, 3.4);
auto[a1, a2, a3] = t3;
}
c++17에서는 구조체에 대해 [] 괄호를 이용하여 한번에 받을 수 있습니다.
'C++' 카테고리의 다른 글
C++ Explicit Conversion Operator (0) | 2020.03.25 |
---|---|
c++ 변환 연산자, 변환 생성자 (0) | 2020.03.23 |
c++ Trivial (2) | 2020.03.19 |
C++ name mangling (0) | 2020.03.11 |
C++ 상수 멤버 함수 operator new 재정의 (0) | 2020.03.11 |