2. auto
●대입하는 값 형태에 따라 컴파일러가 판단하여 변수타입을 정
의함.
●컴파일러가 판단해야하므로 변수는 반드시 초기화.
auto i = 10; // int
auto k; // error!
for ( auto ib = mystl.begin(), ie = mystl.end(); ib != ie; ib++
) { ... }
3. auto
●리턴 타입을 함수 마지막에 적는 형식
●auto function (parameters) -> returntype { ... }
●decltype과 함께 메타 프로그래밍 할 때 유용
auto function(int a) -> int { return a; }
int function(int a) { return a; }
auto function(int a, double b) -> decltype(a*b) { return a*b; }
decltype(a*b) function(int a, double b) { return a*b; } // error! -
a, b가 아직 나오지 않아 추론할 수 없음
4. decltype
●선언한 타입을 반환하는 것으로 메타 프로그래밍용.
●인자에 들어오는 것 어떠한 것도 실행하지 않음.
struct A { double x; };
const A a = { 1.0 };
const double b = 1.0;
decltype(a.x) ac = 1.0;
decltype(b) bc = 1.0;
ac = 3.0;
//bc = 3.0; - error `bc' is `const double'.
6. static_assert
●컴파일 타임에 조건을 검사하여 오류 발생.
●조건식은 반드시 상수 비교
#define TEST 1
...
static_assert(TEST==0, "Error!"); // compile error!
7. lamda
●이름 없는 함수
●STL류에서 Functor를 만들 때, 편리
●형식: [captures] (parameters) -> returntype { /* implement */ } ();
o[] { return 3.14; } (); // 실행
oauto functor_1 = [] (int a) -> int { return a; }; // 구현 및 대입
int iv[] = { 2, 9, 3, 1, 7, 6 };
sort(iv, iv+6, [] (int a, int b) -> bool{ return a < b; });
for_each(iv, iv+6, [] (int a) { cout << a << endl; } );
8. using
●이름 재정의 - typedef와 다름
●typedef는 타입에 대한 alias를 추가하는 것이지 새로운 타입을
추가하는 것이 아님 - 약한 형식 검사
●범위를 정할 수 있음.
using NewName = OldName;
using Namespace::Name; == using Name = Namespace::Name;
int i; using r = i; == int i; int& r = i;
using Cos = std::cos; != using C = std::cos(double);
9. enum
●enum에 타입을 줄 수 있음. (기본형 int)
●enum의 변수의 범위 지정 가능. (기본은 글로벌)
oenum class Name : Type { enums... };
enum class E : unsigned int { E1, E2, E3 };
enum class F : unsigned int { E1, E2, E3 };
int
main(int,char*[])
{
E e = E::E1;
F f = F::E1;
}
10. friend
●typedef 로 정의한 타입도 추가 가능
●템플릿 인수 사용 가능
class C;
typedef Ctype C;
template<typename _T>
class X1 {
friend class C;
friend class Ctype;
friend class _T;
};
11. for
●범위 기반 반복
int iv[] = { 1, 2, 9, 3, 6 };
for ( int& i : iv ) cout << i << endl;
vector<int> isv = { 1, 2, 9, 3, 6 };
for ( int i : isv ) cout << i << endl;
12. >>
●기존에는 '>>'를 무조건 우측 시프트 연산자로 인식
●Nested Template 사용 시 띄어 쓰지 않아도 됨
#include <vector>
using namespace std;
typedef vector<vector<int>> double_vector;
13. delegating constructor
●같은 클래스 내에 다른 생성자에게 위임
class MyClass {
public:
MyClass(int a, int b) { ... }
MyClass() : MyClass(0, 0) { ... }
MyClass(const MyClass& obj) : MyClass(obj.a, obj.b) { ... }
};
14. inheriting constructor
●부모 클래스 생성자를 암묵적으로 상속.
●클래스 내 using Parent::Parent; 구문을 사용하여 상속.
●using Parent::Parent(...); 구문으로 일부 상속 가능.
●자식 멤버 변수 초기화는 하지 않으니 주의.
●기본생성자와 복사생성자는 상속하지 않으니 주의.
class Parent { public: Parent(int a) { ... } };
class Child {
public:
using Parent::Parent;
int a;
};
15. constexpr
●수식 또는 함수가 상수 표현식인 것을 명시하여, 상수만을 필
요로 하는 문법에 사용할 수 있도록 함.
constexpr int size(void) { return 1+5; }
int v[size()];