⭐ Game Programming/C++

C++14 에 추가된 기능 정리

테디슨 2021. 9. 19. 23:02

C++14

C++ 14의 새로운 기능들을 정리하고자 한다.

1. Binary literal

Binary literal은 2진법 숫자를 나타내는 표기법이다.
기존의 16진수 앞에 0x가 붙은것처럼 2진수 앞에는 0b가 붙는다.
또한 ' 문자로 숫자를 구분지을 수 있다.

int b = ob110;  // 6;
int b2 = 0b1111'1111

2. Generic lambda

C++11 까지는 lambda 함수의 인자타입이 명시적으로 적었어야했다.
람다 함수의 인자는 auto 키워드를 가질수 없어서 인자타입마다 람다 함수를 모두 만들어야 했다.

auto intAdd = [] (int a, int b) -> int { return a + b; }
auto floatAdd = [] (float a, float b) -> float { return a + b; };

int iA = intAdd(10, 20);
float fA = floatAdd(1.1f, 2.2f);

C++14부터 이러한 제약이 없어지고 람다 함수의 인자에 auto 키워드를 사용할 수 있게 되었다.

auto add = [] (auto a, auto b) { return a + b; }

int iA = add(10, 20);
float fA = add(1.1f, 2.2f);

3. Lambda capture initializers

람다 함수 외부에 선언되지 않은 멤버를 람다 함수안에서 선언하고 초기화 할 수 있고. 값 이동 capture가 가능해 졌다.

auto initLambda = [ x = 10 ] { return x * 2; }   //return 20

int num = initLambda();

std::unique_ptr<int> uptr(new int(100));
auto moveLambda = [ptr = std::move(uptr)] { return *ptr; }
auto uptr2 = std::move(moveLambda);

4. return type deduction

auto를 반환 타입으로 지정하면 컴파일러가 타입을 추론한다.
람다에 auto를 반환 타입으로 지정하여 타입을 추론하게 할 수 있다.

auto f(int i)  { return i; }

template<typename T>
auto& f(T& t) { return t; }

auto g = [](auto& x) -> auto& { return f(x); }
int y = 10;
int& z = g(y);

5. Relaxing constraints on constexpr functions

constexpr 함수에대한 제약이 완화되어 함수내 if나 재귀 함수 호출이 가능하도록 변경 되었다.

constexpr int factorial(int n) {
  if (n <= 1) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}
factorial(5); // == 120

6. Variable template

변수의 템플릿화가 가능하게 되었다.

template<class T>
constexpr T pi = T(3.1415926535897932385);
template<class T>
constexpr T e  = T(2.7182818284590452353);
반응형