I am developing a tree-like data structure for a numerical simulation package, based on a composite type named Tree
. To keep things general, I keep the implementation dimension-agnostic, so it should work with 1D, 2D, and 3D trees (i.e., binary tree, quadtree, octree). However, I would also like to keep the code as fast as possible, i.e., have the dimensionality as a compile-time constant. How would I implement this properly in Julia?
My first attempt is to write the struct as follows
mutable struct Tree{D}
# implementation...
end
and then write functions as foo(t::Tree)
or bar(t::Tree{D}) where D
depending on whether I need to access the dimension in the respective function body. However, I am wondering:
- Is this in fact the right way to do it or is there a better way?
- Does the compiler even “know”
D
wherever it is needed, or will it actually be a runtime value?
Note: As you might have guessed, I am coming from a C++ background, where the canonical way to implement such a behavior (i.e., having an integer as a compile-time constant) would be to use a non-type template parameter:
template <int D> struct Tree {
// implementation...
};