Skip to content

Instantly share code, notes, and snippets.

@MikimotoH
Created July 3, 2014 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikimotoH/282dca62e08b90b9b673 to your computer and use it in GitHub Desktop.
Save MikimotoH/282dca62e08b90b9b673 to your computer and use it in GitHub Desktop.
C++ Template MetaProgramming to calculate Square Root
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