Skip to content

Instantly share code, notes, and snippets.

@mistificator
Created June 18, 2026 22:24
Show Gist options
  • Select an option

  • Save mistificator/4ca599e33518708cefe514656de31e67 to your computer and use it in GitHub Desktop.

Select an option

Save mistificator/4ca599e33518708cefe514656de31e67 to your computer and use it in GitHub Desktop.
collection_cast.h
#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

Copy link
Copy Markdown
Author
int main() {
    std::vector<int> input_vec = {10, 20, 30};

    auto conv = [](auto value) { 
        return std::to_string(value); 
    };

    auto output_vec = collection_cast(input_vec, conv);

    for (const auto& str : output_vec) {
        std::cout << str << " "; // 10 20 30
    }

    return 0;
}

@mistificator

Copy link
Copy Markdown
Author
struct {
    template <typename T>
    std::string operator()(const T& value) const {
        return std::to_string(value);
    }
} conv;

int main() {
    std::vector<int> input_vec = {1, 2, 3};

    auto output_vec = collection_cast(input_vec, conv); 
}

@mistificator

Copy link
Copy Markdown
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