Created
July 3, 2014 15:04
-
-
Save MikimotoH/282dca62e08b90b9b673 to your computer and use it in GitHub Desktop.
C++ Template MetaProgramming to calculate Square Root
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template<int N, int i> | |
struct SqrtM{ | |
enum{ | |
ret = (i*i <= N && (i + 1)*(i + 1) > N)? i : SqrtM<N, i - 1>::ret | |
}; | |
}; | |
template<int N> | |
struct SqrtM<N,0>{ | |
enum{ | |
ret = 0 | |
}; | |
}; | |
template<int N> | |
struct Sqrt{ | |
enum{ret = SqrtM<N,N/2>::ret}; | |
}; | |
template<> | |
struct Sqrt < 1 > { | |
enum{ ret = 1 }; | |
}; | |
template<> | |
struct Sqrt < 0 > { | |
enum{ ret = 0 }; | |
}; | |
int main(){ | |
static_assert(Sqrt<2>::ret==1, ""); | |
static_assert(Sqrt<3>::ret == 1, ""); | |
static_assert(Sqrt<4>::ret == 2, ""); | |
static_assert(Sqrt<9>::ret == 3, ""); | |
static_assert(Sqrt<10>::ret == 3, ""); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment