Created
June 18, 2026 22:24
-
-
Save mistificator/4ca599e33518708cefe514656de31e67 to your computer and use it in GitHub Desktop.
collection_cast.h
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 <iostream> | |
| #include <vector> | |
| #include <string> | |
| #include <algorithm> | |
| #include <utility> | |
| #include <iterator> | |
| template < | |
| template <typename...> class Container, | |
| typename OldType, | |
| typename... Args, | |
| typename Converter | |
| > | |
| auto collection_cast(const Container<OldType, Args...>& source, Converter converter) | |
| { | |
| using NewType = decltype(converter(std::declval<const OldType&>())); | |
| Container<NewType> target; | |
| std::transform( | |
| source.begin(), | |
| source.end(), | |
| std::inserter(target, target.end()), | |
| converter | |
| ); | |
| return target; | |
| } |
mistificator
commented
Jun 18, 2026
Author
Author
std::string append_prefix(const std::string& prefix, int value) {
return prefix + std::to_string(value);
}
struct Multiplier {
double factor;
double multiply(int value) const { return value * factor; }
};
int main() {
std::vector<int> numbers = {1, 2, 3};
using namespace std::placeholders;
auto bind_func = std::bind(append_prefix, "ID: ", _1);
auto res_A = collection_cast(numbers, bind_func);
Multiplier calc{1.5};
auto bind_method = std::bind(&Multiplier::multiply, &calc, _1);
auto res_B = collection_cast(numbers, bind_method);
for (const auto& s : res_A) std::cout << s << " "; // ID: 1 ID: 2 ID: 3
std::cout << "\n";
for (const auto& d : res_B) std::cout << d << " "; // 1.5 3 4.5
return 0;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment