Generic, based on constant value

I have a function, which has special cases for 2 and 3 for some constant (number of splits in the tree). Starting from 4 there is a generic algorithm which is slower, but universal.

I want to have few implementations of my function for cases when constant is 2, 3, and for everything else.

I can do it with different names and match, but I feel that 'impl' is really good description of what I do.

Is there a way to (at type level) say that

impl Search for Tree when BRANCHES=2 {
...
}

impl Search for Tree when BRANCHES=3 {
...
}

impl Search for Tree {
// Generic implementation
}

You can do this:

impl Search for Tree {
    pub fn search(&mut self) {
        match self.branches {
            2 => self.search_2(),
            3 => self.search_3(),
            _ => self.search_all(),
        }
    }
    
    pub fn search_2(&mut self) {}
    pub fn search_3(&mut self) {}
    pub fn search_all(&mut self) {}
}

I don't think there are nicer ways to write it.

2 Likes

I'm not really sure what BRANCHES is here. Is it a compile time constant? Perhaps you could use conditional compilation (something like #[cfg(BRANCHES = "2")].)

2 Likes

trentj, I like this. It's a compile time constant for 'code tweaks', so moving it into build configuration is reasonable.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.