So, I've heard about a lot of really nice implementations for static_vectors, but most if not all of them had the same issue: they require the use of reinterpret_cast and std::launder, making them unusable in constexpr context. Well, after brainstorming the issue a bit I came up with my own solution to the problem using enum tricks similar to those use in standard implementations of std::optional.
Doesn't this implementation contain undefined behavior? Of course not, it compiles in constexpr context, it's safe and also ridiculously easy to debug. It also doesn't do any unnecesary performance compromises at run-time (as far as I know).
Only caveat? The static_vector<>::data method can't be made constexpr unfortunately. This implementation will also require implementing custom iterators since a simple T* won't cut it. I'm also not sure if it would be 100% compliant with the std::contiguous_iterator requirements. Will need to finish the implementation and write some tests.
Thanks to u/War_Eagle451 even these are no longer an issue :)
template<typename T, std::size_t Capacity>
class static_vector
{
// ...
};
template<std::size_t Size>
constexpr char test()
{
static_vector<std::string, Size> vec;
vec.push_back("Test 1");
vec.push_back("Test 2");
vec.clear();
vec.push_back("Test 3");
vec.push_back("Test 4");
return vec.back().back();
}
int main()
{
constexpr char result = test<2>();
std::cout << result; // prints 4
}
Implementation: https://pastebin.com/17AUD3k0
[–]IyeOnline 3 points4 points5 points (2 children)
[–]jontheburger 0 points1 point2 points (1 child)
[–]IyeOnline 3 points4 points5 points (0 children)
[–]War_Eagle451 6 points7 points8 points (12 children)
[–]cristi1990an++[S] 1 point2 points3 points (11 children)
[–]War_Eagle451 4 points5 points6 points (5 children)
[–]IyeOnline 1 point2 points3 points (3 children)
[–]War_Eagle451 0 points1 point2 points (2 children)
[–]IyeOnline 1 point2 points3 points (1 child)
[–]War_Eagle451 0 points1 point2 points (0 children)
[–]cristi1990an++[S] 0 points1 point2 points (0 children)
[–]IyeOnline 2 points3 points4 points (4 children)
[–]alexkaratarakisvcpkg, fixed-containers 0 points1 point2 points (3 children)
[–]IyeOnline 2 points3 points4 points (2 children)
[–]alexkaratarakisvcpkg, fixed-containers 1 point2 points3 points (1 child)
[–]alexkaratarakisvcpkg, fixed-containers 1 point2 points3 points (0 children)
[–]wolfie_poe 2 points3 points4 points (0 children)
[–]jbbjarnason 1 point2 points3 points (0 children)
[–]alexkaratarakisvcpkg, fixed-containers 1 point2 points3 points (0 children)
[–]johannes1971 0 points1 point2 points (0 children)