C++ doesn't support function overloading with multiple return types. So if you create a function int rand()
, it will have to return an int unless you create other functions with different arguments.
Regarding the creation of random numbers, the STL has a library just for that. Take a look at the <random>
header.
Regarding the redefinition of a rand()
function, you can do it as long as you don't include the <stdlib.h>
header file. The compiler and the linker will be smart enough to know which function you want to use. But this method prevents you from using the rand()
function in the libc.
If you want to create a rand()
function which can return any type, I think you have to use a template. Unfortunatly, the API will not be as simple as the one you gave.
template<typename type>
type rand()
{
...
}
struct C {};
int main()
{
auto a = rand<int>();
auto b = rand<double>();
auto c = rand<C>();
}
This example compiles, so it should be fine for your needs. Although, I think redefining rand like this may not be a good idea.
Finally, if you are on Linux, you can dynamically change the functions called by an executable using the LD_PRELOAD
environment variable. Which, I guess is another way to do what you said (but a very bad idea in my opinion).