Skip to content

Instantly share code, notes, and snippets.

@plutooo
Created September 9, 2019 02:37
Show Gist options
  • Save plutooo/7f641ff38c6ad50372868d91dd42c5d0 to your computer and use it in GitHub Desktop.
Save plutooo/7f641ff38c6ad50372868d91dd42c5d0 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "RandomChoice.h"
class Base { public: virtual const char* Get() = 0; virtual ~Base() = default; };
class A : public Base { public: const char* Get() { return "A"; } };
class B : public Base { public: const char* Get() { return "B"; } };
class C : public Base { public: const char* Get() { return "C"; } };
int main(int argc, char* argv[])
{
srand(time(NULL));
printf("%d\n", RandomChoice(2, 3, 5, 7, 11, 13));
printf("%s\n", RandomChoice("Bob", "Alice"));
printf("%d\n", RandomChoice<int (*)()>([] { return 2; }, [] { return 3; } )());
Base* obj = RandomChoiceNew<Base*, A, B, C>();
printf("%s\n", obj->Get());
delete obj;
return 0;
}
#include <utility>
template <typename T, typename U>
T RandomChoice_Recursive(unsigned choice, unsigned i, U a)
{
return a;
}
template <typename T, typename U, typename... TArgs>
T RandomChoice_Recursive(unsigned choice, unsigned i, U a, TArgs... tail)
{
if (i == choice)
return a;
else
return RandomChoice_Recursive<T>(choice, i+1, std::forward<TArgs>(tail)...);
}
template <typename T, typename... TArgs>
T RandomChoice(T a, TArgs... tail)
{
unsigned num = sizeof...(TArgs) + 1;
unsigned choice = rand();
choice %= num;
return RandomChoice_Recursive<T>(choice, 0, std::forward<T>(a), std::forward<TArgs>(tail)...);
}
template <typename T, typename U, typename... UArgs>
T RandomChoiceNew_Recursive(unsigned choice, unsigned i, UArgs... args)
{
return new U(args...);
}
template <typename T, typename U, typename V, typename... TArgs, typename... UArgs>
T RandomChoiceNew_Recursive(unsigned choice, unsigned i, UArgs... args)
{
if (i == choice)
return new U(args...);
else
return RandomChoiceNew_Recursive<T, V, TArgs...>(choice, i+1, std::forward<UArgs>(args)...);
}
template <typename T, typename... TArgs, typename... UArgs>
T RandomChoiceNew(UArgs... args)
{
unsigned num = sizeof...(TArgs) + 1;
unsigned choice = rand();
choice %= num;
return RandomChoiceNew_Recursive<T, TArgs...>(choice, 0, std::forward<UArgs>(args)...);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment