목록C++ (29)
헤더파일
// 컨테이너의 모든 요소를 출력하는 함수. template void show(T& c) { //auto p1 = c.begin(); //auto p2 = c.end(); auto p1 = begin(c); auto p2 = end(c); while (p1 != p2) { cout decltype(c.end()) { return c.end(); } // arr version template constexpr T* begin(T(&arr)[N]) { return arr; } template constexpr T* end(T(&arr)[N]) { return arr + N; } int main() { list s = { 1,2,3 }; int x[3] = { 1,2,3 }; auto p1 = begin(s)..
assert는 실행시간에 표현식이 거짓이면 프로그램을 종료합니다. c++11에서 추가된 static_assert는 컴파일 타임에 판단하여 거짓이면 컴파일이 실패합니다. void foo(int age) { assert(age>0); static_assert(age >0, "error");//변수는 컴파일 타임에 판단 불가능, 사용 X static_assert(1
class Point { int x, y; public: explicit Point(int a, int b) : x(a), y(b) {} }; void foo(Point p) {} int main() { foo({ 1,1 }); //Point p1(1, 1); //Point p2{ 1, 1 };// direct initialize //Point p3 = { 1, 1 };// copy initialize. error } p3 초기화는 explicit가 없다면 복사 생성자가 실행되어 초기화 됩니다. 하지만 explicit를 넣어준다면 불필요한 복사생성을 막을 수 있습니다.
void true_function() {} class istream // basic_istream { public: bool fail() { return false; } // 방법 1. bool 로 변환 - 단점. shift 연산이 허용된다. //operator bool() { return fail() ? false : true; } // 방법 2. void* 로의 변환 - C++ 98/03 // operator void*() { return fail() ? 0 : this; } // 방법 3. 함수 포인터로의 변환. //typedef void(*F)(); //operator F() { return fail() ? 0 : &true_function; } // 방법 4. 멤버 함수 포인터로의 변환. - S..
class Point { int x, y; public: Point() : x(0), y(0) {} Point(int a, int b) : x(a), y(b) {} Point(int a) : x(0),y(a){} // 변환 연산자 : 객체를 다른 타입으로 변환할때 호출된다. // 특징 : 리턴 타입을 표기하지 않는다. operator int() { return x; } }; int main() { int n = 3; double d = n; // 암시적 형변환 발생. Point p1(1, 2); n = p1;// p1.operator int() cout
int ret = foo(); if (ret == 0) { } // C++17 스타일 // if ( init 구문; 조건문 ) if (int ret = foo(); ret == 0) { cout
Trivial은 쓸모가 없는 이라는 뜻입니다. is_trivial_*::value 를 통해 해당 타입의 생성자, 복사생성자가 유효한지 확인할 수 있습니다. #include #include using namespace std; class A { public: virtual void foo() {} }; int main() { cout
name mangling c++에서 지원하는 함수 오버로딩은 같은 함수이름으로 여러 타입을 지원하게 해주지만 어셈블리에서는 함수이름 하나당 하나의 정의만 가능하기 때문에 컴파일 하게 되면 오버로드된 함수에 따라 함수이름이 변하게 됩니다. 이러한 현상을 name mangling 이라고 합니다. c 파일과 cpp 파일을 동시에 컴파일 한다면 name mangling 현상 때문에 오류가 발생합니다. cpp 컴파일러와 c 컴파일러가 같은 함수라도 어셈블리 형태가 다르기 때문인데 이럴 경우 아래와 같은 전처리기를 사용하여 해결합니다. #indef __cplusplus extern "C" { #endif // 함수들 #indef __cplusplus } #endif .c 파일에 정의된 printf 함수를 cpp에서..