Created
November 21, 2023 05:01
-
-
Save jonwis/e08ecd37f3513565bb8dfa3d1345cf2e to your computer and use it in GitHub Desktop.
A function that transmutes any container into a vector of another type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <algorithm> | |
#include <iterator> | |
#include <functional> | |
// Given a container that supports "begin(c)" / "end(c)", uses std::transform plus a | |
// provided transmutor function to produce an output vector of the results. The | |
// type of the vector returned is derived from the return type of the transmutor | |
// operation. | |
template<typename Z, typename Q> | |
auto transmute(Z const& container, Q&& transmutor) -> std::vector<decltype(std::invoke(transmutor, *std::begin(container)))> | |
{ | |
std::vector<decltype(std::invoke(std::forward<Q>(transmutor), *std::begin(container)))> results; | |
std::transform(std::begin(container), std::end(container), std::back_inserter(results), std::forward<Q>(transmutor)); | |
return results; | |
} | |
// Example using the transmute function to switch an array of integers into | |
// a vector of floats | |
std::vector<float> convert(std::array<int, 4> const& items) | |
{ | |
return transmute(items, [](int f) { return static_cast<float>(f); }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment