Skip to content
This repository has been archived by the owner on Dec 4, 2020. It is now read-only.

Add GetRandomElement helpers and cleanup tpzrand #1485

Merged
merged 1 commit into from
Nov 8, 2020
Merged

Add GetRandomElement helpers and cleanup tpzrand #1485

merged 1 commit into from
Nov 8, 2020

Conversation

zach2good
Copy link
Contributor

@zach2good zach2good commented Nov 8, 2020

This allows:

std::vector<int> v{ 1, 2, 3, 4, 5 };
auto ptrToV = &v;

tpzrand::GetRandomElement(v);
tpzrand::GetRandomElement(ptrToV);
tpzrand::GetRandomElement({ 1, 2, 3, 4, 5 });

... on any type that has at() and size().

For the C++ nerds out there, I tried to use SFINAE to validate if passed in containers had access to at() and size(), but template voodoo isn't my speciality. I got as far as:

template <typename T, typename Enable = void>
inline constexpr bool is_container_like = false;

template <typename T>
inline constexpr bool is_container_like
<T, std::void_t<
    decltype(std::declval<T>().at()),
    decltype(std::declval<T>().size())>
> = true;

template <typename T>
static inline auto GetRandomElement(T* container)
-> std::enable_if_t<is_container_like<T>, typename T::value_type>
{
    return container->at(GetRandomNumber<std::size_t>(0U, container->size()));
}

🤷

I affirm:

  • that I agree to Project Topaz's Limited Contributor License Agreement, as written on this date
  • that I've tested my code since the last commit in the PR, and will test after any later commits

@zach2good zach2good merged commit 72b91ac into project-topaz:release Nov 8, 2020
@zach2good zach2good deleted the get_random_element branch November 8, 2020 09:37
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants