cpp_constexpr - 8BitsCoding/RobotMentor GitHub Wiki
constexpr์ค๋ช ์ ์์ ์๋ ์์๋ฅผ ๋จผ์ ๋ณด์
// ํ
ํ๋ฆฟ ๋ฉํํ๋ก๊ทธ๋๋ฐ
template <int T>
struct Fibonacci
{
enum { value = (Fibonacci<T-1>::value + Fibonacci<T-2>::value) };
}
// ์ด ํ
ํ๋ฆฟ ๋ฉํํ๋ก๊ทธ๋๋ฐ์๋ ์กฐ๊ฑด๋ฌธ์ด ์๋ค.
// ๊ทธ ๋์ ๊ตฌ์กฐ์ฒด ์ค๋ฒ๋ก๋ฉ ๊ฐ์ ๋ฐฉ๋ฒ์ ์ฌ์ฉํ์ฌ
// 0, 1, 2์ ๊ฐ์ ํน์ ์ผ์ด์ค๋ฅผ ์ฒ๋ฆฌํ๋ค.
template <>
struct Fibonacci<0>
{
enum { value = 1 };
};
template <>
struct Fibonacci<1>
{
enum { value = 1 };
}
template <>
struct Fibonacci<2>
{
enum { value = 1 };
}
// Main
int x = Fibonacci<45>::value;
cout << x << endl;
- ์ด๋ ๊ฒ ํ ์ด์ ๋ ์คํ์ ์์๊ฐ์ผ๋ก ๋ฃ๊ธฐ์ํจ์ธ๋ฐ ... ๊ทธ์ ๋ฐ๋ฅธ ๋จ์ ์
- ์ฝ๋๋ฅผ ๋ณด๊ธฐ ํ๋ค๊ณ
-
Fibonacci<45>::value;
๊ฐ ํจ์์ธ๊ฐ ์ถ์
constexpr : ์ปดํ์ผ๋ฌ์ผ ํ ์ ์๋ค๋ฉด ๋๊ฐ ์ต์ข ์ ์ผ๋ก ์ด ๊ฐ์ ์์๋ก ๋ฐ๊ฟ์ค
ํ ์ ์๋ค๋ฉด ํจ์๋ก!
constexpr unsigend int fibonacci(unsigned int i)
{
return (i <= 1u) ? i : (fibonacci(i-1) + fibonacci(i-2));
}
-
์ปดํ์ผ ์์ ๊ฐ ํ๊ฐ๋ฅผ ๊ฐ์ ํ๊ธฐ ์ํด์ ํฌํ๋ฆฟ ๋ฉํํ๋ก๊ทธ๋๋ฐ์ ๋จ์ฉ!
-
์ด๋ฌ์ง ์์๋ ์ปดํ์ผ๋ฌ๊ฐ ์๋ฐ์ ์ผ๋ก ๊ทธ๋ ๊ฒ ํด์ฃผ๋ ๊ฒฝ์ฐ๋ ์๊ธฐ๋ ํจ
-
constexpr๊ฐ ํ๋ก๊ทธ๋๋จธ์ ์๋๋ฅผ ๋ณด์ฌ์ฃผ๋ ๋ ๋์ ๋ฐฉ๋ฒ!
-
์ฐ๋ฆฌ์ ์๋๋ ์ปดํ์ผ ๋์ค์ ๊ฐ์ ํ๊ฐํ๋ ๊ฒ!
-
์ปดํ์ผ๋ฌ๊ฐ ์ปดํ์ผ ๋์ค์ ๋ณ์๋ค์ ๊ฒฐ์ ์ง์ด ์ค๋ค.
-
ํจ์๋ ์ต๋ํ ๊ฒฐ์ ์ง์ด์ฃผ๋ ค ๋ ธ๋ ฅ!
constexpr int Factorial(int n)
{
return n <= 1 ? 1 : n * Factorial(n-1);
}
// Main
int value = 3;
int result1 = Factorial(value); // Ok
constexpr int result2 = Factorial(value);
// Compile Error : value๊ฐ ๋ณ์์ด๊ธฐ์ ์ปดํ์ผ๋ฌ ์
์ฅ์์๋ ๊ฐ์ ์ ํด์ฃผ์ง ๋ชปํ๋ค.
constexpr int result3 = Factorial(3); // Ok
์ถ๊ฐ์ ์ผ๋ก Factorial(30)๋ฑ ๊ณ์ฐ์ด ๋ง์์ง๋ฉด constexpr์ ๋ชป์ฐ๊ฒ ๋ง๋๋ค.
constexpr int result3 = Factorial(30);
๋ ์ปดํ์ผ ์๋ฌ์
- ๋ณ๊ฒฝ์ ๋ถํํ๋ค.
- ์ปดํ์ผ ์์ ํ๊ฐํด์ฃผ์์ผ๋ฉด ์ข๊ฒ ๋ค.
ํ๋ฏธ...? ์ญ์ ์์๋ก ์ค๋ช
const int num = 1; // Ok
num = 10; // Comfile Error
constexpr int num1 = 2; // Ok
num1 = 10; // Comfile Error
int num2 = 3;
constexpr int num3 = num2; // Comfile Error
const int num4 = 4;
constexpr int num5 = num4; // Ok
constexpr int num6 = 6; // Ok
constexpr int num7 = num6; // Ok
- ๋ฉค๋ฒ ํจ์์๋ง ์ฌ์ฉ ๊ฐ๋ฅ
- ๋ฉค๋ฒ ๋ณ์๋ฅผ ๋ฐ๊ฟ ์ ์์
- ๋ฉค๋ฒ์ ๋น๋ฉค๋ฒ ํจ์์ ๋๋ค ์ฌ์ฉ๊ฐ๋ฅ
- C++14๋ถํฐ๋ ๋ฉค๋ฒ ๋ณ์๋ฅผ ๋ฐ๊ฟ ์ ์์
constexpr int Fibonacci(int i) {} // Ok
int Fibonacci(int i) {} const // Comfile Error : ์ ์์น์ const์๋ค๋ ์์ฒด๊ฐ ์ปดํ์ผ ์๋ฌ์
constexpr int Champion::GetWinCount() // Ok (C++14)
{
mWinCount = 10;
return mWinCount;
}
constexpr int Champion::GetWinCount() const
{
mWinCount = 10; // Comfile Error
return mWinCount;
}
class FixedArray
{
public:
// ...
private:
enum { MAX = 10 };
int mArray[MAX];
}
class FixedArray
{
public:
// ...
private:
static constexpr int MAX = 10;
int mArray[MAX];
}
ํ์ง๋ง ... enum์ด ๋ ๊น๋ํ์ง ์๋?
ํน๋ณํ ์ด์ ๊ฐ ์๋ค๋ฉด enum์ฐ์