I have an interface that deals with any container type. std::vector
, std::array
, and even std::basic_string
. The issue is that there is nothing to prevent someone from passing a container that does not have continguous memory.
The current solution I have is to delete
those interface I want to prevent.
void dosoemthing(const std::list&)=delete;
void dosoemthing(const std::map&)=delete;
However, I would prefer if I could just add a static assertion based on the type trait. Which leads to my question. Does their exist a type trait for containers that can be used to identify if its memory is contiguous? I have been coming through the documentation and have yet to find anything. I figured before marking it a lost cause I would check with the A team.
You can bring your own type trait, and then use static_assert
to verify it:
#include <type_traits>
#include <vector>
#include <array>
template<typename T>
struct has_contiguous_memory : std::false_type {};
template<typename T, typename U>
struct has_contiguous_memory<std::vector<T, U>> : std::true_type {};
template<typename T>
struct has_contiguous_memory<std::vector<bool, T>> : std::false_type {};
template<typename T, typename U, typename V>
struct has_contiguous_memory<std::basic_string<T, U, V>> : std::true_type {};
template<typename T, std::size_t N>
struct has_contiguous_memory<std::array<T, N>> : std::true_type {};
template<typename T>
struct has_contiguous_memory<T[]> : std::true_type {};
template<typename T, std::size_t N>
struct has_contiguous_memory<T[N]> : std::true_type {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With