I've decided to host a contest in C++.
This contest involves template metaprogramming, therefore, the language is required to be C++. If you find this task hard, don't worry, because template programming is quite tricky!
The goal is to write a templated struct or class which contains a member which is the square root of the template argument. The struct must be written in this form:
it must be called 'SquareRoot' and it must have a member called 'v' which contains the integer i for whichCode:template<int x /*other arguments allowed, but must have default values*/ > struct SquareRoot { static const int v = /* integer part of sqrt(x) */ /*other members allowed*/ };
i <= sqrt(x) < i + 1
which means that i contains the truncated value of sqrt(x).
Example;
Code:cout << SquareRoot<9>::v; //Must output 3 cout << SquareRoot<1000>::v; //Must output 31 cout << SquareRoot<82>::v; //Must output 9
//
The following criterias are considered (in order) to determine the winner of the contest:
Some other rules:
- The maximum value of x for which the program compiles (maximum 2^31-1 on my machine) and gives the correct value.
x will not be smaller than 1.- The shortest source code, measured in bytes
- The time when the email with the solution arrived.
After the deadline, it'll probably take a day or two to judge the contest, depending on the number of entries and different compilers used.
- It is allowed to 'update' your solution if you find a better one.
- The deadline is Sunday, October, 3rd
- Entries should be mailed to [email protected]
- My primary compiler is MSVC++.NET; if you use another one, please specify in your entry (please use free compilers).
Microsofts latest C++ compiler can be downloaded for free here.- The calculation must be done entirely in the compiler. As an example, this code must be able to compile:
Code:char data[ SquareRoot<16>::v ];
The winner will recieve... well... some reputation.
I cannot think of anything more right now.
UPDATE:
The first criteria of judgement is very compiler-dependent. Hopefully, every entry will will compile in the same compiler.
Please post in this thread if you're participating!
These are the people that have submitted entries which complies for at least some values of x:
A number of people (4) have submitted solutions involving the use of std::sqrt. These solutions will not work, because the value of SquareRoot<x>::v must be known at compile time.
- Fordy
- Okinrus
- Mr Wizard
- LuckY
- xErath