다음과 같은 걸 할 수 있다.
1 2 3 4 5 6 | constexpr int getDefaultArraySize ( int multiplier) { return 10 * multiplier; } int my_array[ getDefaultArraySize( 3 ) ]; |
제약 사항
- It must consist of a single return statement.(typedef, using declaration, using directive, static_assert()는 허용됨)
- It can call only other constexpr functions.
- It can reference only constexpr global variables.
* Recursion은 허용됨
Example of constexpr function
1 2 3 4 | constexpr factorial ( int n) { return n > 0 ? n * factorial( n - 1 ) : 1; } |
constexpr and run time
function argument가 non-constant일 경우, run time에 호출될 수 있다.
이는 compile time과 run time용의 별도의 function을 만들 필요가 없음을 말한다.
1 2 3 | int n; cin >> n; factorial( n ); |
Using objects at compile time
다음과 같은 class가 있다.
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Circle { public : Circle ( int x, int y, int radius) : _x( x ), _y( y ), _radius( radius ) {} double getArea () const { return _radius * _radius * 3.1415926; } private : int _x; int _y; int _radius; }; |
다음과 같이 compile time에 생성하고 면적을 얻으려면 어떻게 하면 되나?
1 2 | constexpr Circle c( 0, 0, 10 ); constexpr double area = c.getArea(); |
constructor와 getArea()가 constexpr이어야 한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Circle { public : constexpr Circle ( int x, int y, int radius) : _x( x ), _y( y ), _radius( radius ) {} constexpr double getArea () { return _radius * _radius * 3.1415926; } private : int _x; int _y; int _radius; }; |
constexpr constructor는 empty body를 가져야 하며, member initializer들 또한 compile time constant이어야 한다.
'programming > C++' 카테고리의 다른 글
Universal reference (0) | 2013.02.18 |
---|---|
shared_ptr, unique_ptr (0) | 2013.02.18 |
std::async and std::future 쓸 때... (0) | 2013.02.18 |
Uniform initialization in C++11 (0) | 2013.02.18 |
Three Optimization Tips for C++ (0) | 2013.02.18 |