Last active
January 10, 2024 19:12
-
-
Save sim642/9184484 to your computer and use it in GitHub Desktop.
Multidimensional std::vector creation wrapper
This file contains 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 "multivector.hpp" | |
using namespace std; | |
int main() | |
{ | |
auto v = make_multivector(3, 2, 1, 5, 0.5); | |
for (auto x : v) | |
{ | |
for (auto y : x) | |
{ | |
for (auto z : y) | |
{ | |
for (auto w : z) | |
cout << w << " "; | |
cout << endl; | |
} | |
cout << endl; | |
} | |
cout << string(10, '-') << endl; | |
} | |
return 0; | |
} |
This file contains 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
#ifndef MULTIVECTOR_H | |
#define MULTIVECTOR_H | |
#include <vector> | |
#include <type_traits> // enable_if | |
#include <cstddef> // size_t | |
/// get type of last element in parameter pack | |
template<typename T, typename... Ts> | |
struct lasttype : lasttype<Ts...> | |
{ | |
}; | |
template<typename T> | |
struct lasttype<T> | |
{ | |
typedef T type; | |
}; | |
template<typename... Ts> | |
using lasttype_t = typename lasttype<Ts...>::type; | |
/// get type of D dimensional structure of vectors of internal type T | |
template<size_t D, typename T> | |
struct multivector | |
{ | |
typedef std::vector<typename multivector<D - 1, T>::type> type; | |
}; | |
template<typename T> | |
struct multivector<0, T> | |
{ | |
typedef T type; | |
}; | |
template<size_t D, typename T> | |
using multivector_t = typename multivector<D, T>::type; | |
/// create a multivector of specific dimensionality with specified dimension sizes and default value | |
template<size_t D, typename T> | |
typename std::enable_if<D == 0, multivector_t<0, T>>::type make_multivector_(T def) | |
{ | |
return def; | |
} | |
template<size_t D, typename... Args, typename T = lasttype_t<Args...>> | |
typename std::enable_if<(D >= 1), multivector_t<D, T>>::type make_multivector_(size_t i, Args... args) | |
{ | |
return multivector_t<D, T>(i, make_multivector_<D - 1>(args...)); | |
} | |
/// create a multivector with specified dimension sizes and default value | |
template<typename... Args, typename T = lasttype_t<Args...>, size_t D = sizeof...(Args) - 1> | |
typename std::enable_if<(D >= 0), multivector_t<D, T>>::type make_multivector(Args... args) | |
{ | |
return make_multivector_<D>(args...); | |
} | |
#endif // MULTIVECTOR_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment