Skip to content

Instantly share code, notes, and snippets.

@jonwis
Created August 26, 2024 17:03
Show Gist options
  • Save jonwis/c1638061eef54b887faab7d662282f64 to your computer and use it in GitHub Desktop.
Save jonwis/c1638061eef54b887faab7d662282f64 to your computer and use it in GitHub Desktop.
#include <vector>
#include <span>
#include <variant>
#include <memory>
template<typename T, int internal = 25> struct small_vector_optimization : std::span<T const>
{
small_vector_optimization(std::span<T const> src)
{
if (src.size() <= internal)
{
storage = FakeoutDestructable{};
auto& a = std::get<0>(storage);
std::uninitialized_copy_n(src.begin(), src.size(), a.data);
static_cast<std::span<T const>&>(*this) = std::span(a.data, src.size());
}
else
{
storage = std::vector(src.begin(), src.end());
auto& a = std::get<1>(storage);
static_cast<std::span<T const>&>(*this) = a;
}
}
private:
struct FakeoutDestructable
{
T data[internal];
};
std::variant<FakeoutDestructable, std::vector<T>> storage;
};
struct Foo
{
int a;
short b;
};
void ConsumeFoo(Foo const&);
void use(Foo const* src, size_t count)
{
small_vector_optimization<Foo> foos({src, count});
for (auto& f : foos)
{
ConsumeFoo(f);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment