Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type_traits - contiguous memory

Tags:

c++

c++11

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.

like image 657
Freddy Avatar asked Oct 11 '15 17:10

Freddy


1 Answers

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 {};
like image 151
Stas Avatar answered Sep 30 '22 18:09

Stas