Skip to content

Instantly share code, notes, and snippets.

@HeMe2
Last active August 15, 2018 17:53
Show Gist options
  • Save HeMe2/05fe1ece4d2907e8636d5c472771141a to your computer and use it in GitHub Desktop.
Save HeMe2/05fe1ece4d2907e8636d5c472771141a to your computer and use it in GitHub Desktop.
C++ class with adjustable inner array size allocated on stack and at compiletime (requires C++11)
/*
* static_array_allocation.cpp
*
* Created on: Aug 15, 2018
* Author: HeMe2
*/
typedef int my_specific_type;
template<int ARRAY_LEN>
class class_with_inner_array {
public:
// Destructor and all constructors are auto generated
constexpr int get_inner_array_size(void) const{
return ARRAY_LEN;
}
constexpr int get_inner_array_size_alternative(void) const {
return sizeof(the_array) / sizeof(my_specific_type);
}
void register_element(const int & position, const my_specific_type & elem) {
the_array[position] = elem;
}
private:
my_specific_type the_array[ARRAY_LEN];
};
int main(int argc, char ** argv) {
class_with_inner_array<3> instance;
// insert a test element
my_specific_type element = 1;
instance.register_element(0, element);
// some methods can be evaluated at compile time, too
my_specific_type another_array[instance.get_inner_array_size_alternative()];
// create an instance with a different size
class_with_inner_array<60> bigger_instance;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment