Skip to content

Instantly share code, notes, and snippets.

@slwu89
Last active February 24, 2022 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slwu89/735ae68b59542e3aeaecdc39ff763464 to your computer and use it in GitHub Desktop.
Save slwu89/735ae68b59542e3aeaecdc39ff763464 to your computer and use it in GitHub Desktop.
class with a container whose type is a template parameter and the thing it stores is also a template parameter
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
// if we needed containers that took > 2 template args (set?) we could use variadic templates.
template<typename T, template<typename, typename> class C>
struct MyVariable {
std::vector<C<T, std::allocator<T>>> values;
MyVariable(const std::vector<std::vector<T>>& initial_values);
~MyVariable() = default;
void print_values() const;
};
template<typename T, template<typename, typename> class C>
MyVariable<T, C>::MyVariable(const std::vector<std::vector<T>>& initial_values) :
values(initial_values.size()) {
values.reserve(initial_values.size());
for (auto i = 0u; i < initial_values.size(); ++i) {
std::copy(initial_values[i].begin(), initial_values[i].end(), std::back_inserter(values[i]));
};
}
template<typename T, template<typename, typename> class C>
void MyVariable<T, C>::print_values() const {
for (auto i = 0u; i < values.size(); ++i) {
for (auto j = 0u; j < values[i].size(); ++j) {
std::cout << values[i][j] << " - ";
}
}
}
// with variadic templates
template <template <typename, typename...> class C,
typename T, typename... Args>
struct MyVariableVariadic {
std::vector<C<T, Args...>> values;
MyVariableVariadic(const std::vector<std::vector<T>>& initial_values);
~MyVariableVariadic() = default;
void print_values() const;
};
template <template <typename, typename...> class C,
typename T, typename... Args>
MyVariableVariadic<C, T, Args...>::MyVariableVariadic(const std::vector<std::vector<T>>& initial_values) :
values(initial_values.size()) {
values.reserve(initial_values.size());
for (auto i = 0u; i < initial_values.size(); ++i) {
std::copy(initial_values[i].begin(), initial_values[i].end(), std::back_inserter(values[i]));
};
}
template <template <typename, typename...> class C,
typename T, typename... Args>
void MyVariableVariadic<C, T, Args...>::print_values() const {
for (auto i = 0u; i < values.size(); ++i) {
for (auto it = values[i].begin(); it != values[i].end(); ++it) {
std::cout << *it << " - ";
}
}
}
int main()
{
std::vector<std::vector<double>> vals;
vals.emplace_back(std::vector<double>{1.0,2.0,3.0});
vals.emplace_back(std::vector<double>{1.25,2.6,3.85});
MyVariable<double, std::vector> my_var(vals);
my_var.print_values();
MyVariableVariadic<std::list, double> my_var(vals);
my_var.print_values();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment