Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mmimic C++ template functions in Java

Tags:

java

c++

In C++ I can write a template function that takes the data type on which to act as an argument, so that a single function can be reused for more than on data type. Is there a provision for doing a similar thing in Java?

Thanks,
Roger

like image 257
gameover Avatar asked Feb 28 '23 19:02

gameover


1 Answers

This person isn't asking about Generics. He's asking about template functions of the sort that are specified in <algorithm>. The closest you could come in Java would be to define (genericized) Interfaces for each of the function types you want to be able to call and then roll your own utility library that accepted instances of the interfaces as input. For instance you could create the following interface

public interface UnaryOperator<T> {
    public boolean test(T item);
}

and then create a utility class like so

public class Algorithms {
    public static <T> void removeIf(Collection<T> c, UnaryOperator<T> op) {
        Iterator<T> itr;
        for (itr = c.iterator(); itr.hasNext(); ) {
            T item = itr.next();
            if (op.test(item)) {
                itr.remove();
            }
        }
    }
}

You can actually find this pattern in the Apache Commons Collections library, but its its not as flexible or extensive as the C++ algorithm's library. I think given any particular example of the STL functors and algorithms library you'd be able to compose something in Java that's similar, but there's no built in equivalent that I'm aware of. Most people I know (even C++ devs) consider <algorithm> to be pretty arcane.

like image 155
Jherico Avatar answered Mar 05 '23 17:03

Jherico