Skip to content

Instantly share code, notes, and snippets.

@timshen91
Last active July 12, 2016 07:54
Show Gist options
  • Save timshen91/a2564c8247b1825c37654e300ff76def to your computer and use it in GitHub Desktop.
Save timshen91/a2564c8247b1825c37654e300ff76def to your computer and use it in GitHub Desktop.
template<int n>
struct IntT {};
template<typename T, int n>
T& operator<<(T& t, IntT<n>) {
return t << n;
}
template<int n, int m>
constexpr bool operator==(IntT<n>, IntT<m>) {
return n == m;
}
template<int n>
constexpr bool operator==(IntT<n>, int m) {
return n == m;
}
template<int m>
constexpr bool operator==(int n, IntT<m>) {
return n == m;
}
template<int n, int m>
constexpr IntT<n + m> operator+(IntT<n>, IntT<m>) {
return {};
}
template<int n>
constexpr int operator+(IntT<n>, int m) {
return n + m;
}
template<int m>
constexpr int operator+(int n, IntT<m>) {
return n + m;
}
template<int n, int m>
constexpr IntT<n - m> operator-(IntT<n>, IntT<m>) {
return {};
}
template<int n>
constexpr int operator-(IntT<n>, int m) {
return n - m;
}
template<int m>
constexpr int operator-(int n, IntT<m>) {
return n - m;
}
template<int n>
constexpr IntT<n> Int = {};
template<typename T>
constexpr auto Sum(T n) {
if constexpr (n == Int<0>) {
return n;
} else {
return Sum(n-Int<1>) + n;
}
}
constexpr auto Sum(int n) {
if (n == Int<0>) {
return n;
} else {
return Sum(n-Int<1>) + n;
}
}
#include <iostream>
int main() {
std::cout << Sum(Int<3>) << "\n";
int n = 3;
std::cout << Sum(n) << "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment