考虑以下:
template <unsigned N>
struct Fibonacci
{
enum
{
value = Fibonacci<N-1>::value + Fibonacci<N-2>::value
};
};
template <>
struct Fibonacci<1>
{
enum
{
value = 1
};
};
template <>
struct Fibonacci<0>
{
enum
{
value = 0
};
};
Run Code Online (Sandbox Code Playgroud)
这是一个常见的例子,我们可以将Fibonacci数的值作为编译时常量:
int main(void)
{
std::cout << "Fibonacci(15) = ";
std::cout << Fibonacci<15>::value;
std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
但是你显然无法在运行时获得该值:
int main(void)
{
std::srand(static_cast<unsigned>(std::time(0)));
// ensure the table exists up to a certain size
// (even though the rest of the code …Run Code Online (Sandbox Code Playgroud)