48 lines
924 B
C++
48 lines
924 B
C++
/*
|
|
Write a constexpr function template with a non-type template parameter that
|
|
returns the factorial of the template argument. The following program should
|
|
fail to compile when it reaches factorial<-3>().
|
|
|
|
*/
|
|
|
|
template <int N>
|
|
constexpr long long fibonacci() {
|
|
static_assert(N >= 0);
|
|
if constexpr (N <= 1) {
|
|
return N;
|
|
} else {
|
|
return fibonacci<N - 1>() + fibonacci<N - 2>();
|
|
}
|
|
}
|
|
|
|
// int main() {
|
|
// static_assert(fibonacci<1LL>() == 1);
|
|
// // static_assert(factorial<3>() == 6);
|
|
// // static_assert(factorial<5>() == 120);
|
|
//
|
|
// // fibonacci<-3>();
|
|
//
|
|
// return 0;
|
|
// }
|
|
|
|
#include <iostream>
|
|
|
|
template <typename T>
|
|
T add(T x, T y) {
|
|
return x + y;
|
|
}
|
|
|
|
template <typename T>
|
|
T mult(T t, int N) {
|
|
return t * N;
|
|
}
|
|
|
|
int main() {
|
|
std::cout << add(2, 3) << '\n';
|
|
std::cout << add(1.2, 3.4) << '\n';
|
|
|
|
std::cout << mult(2, 3) << '\n';
|
|
std::cout << mult(1.2, 3) << '\n';
|
|
|
|
return 0;
|
|
}
|