Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of C++'s std::bind in Java?

Is there a way to bind parameters parameters to function pointers in Java like you can with std::bind in C++? What would the Java equivalent of something like this be?

void PrintStringInt(const char * s, int n)
{
    std::cout << s << ", " << n << std::endl;
}

void PrintStringString(const char * s, const char * s2)
{
    std::cout << s << ", " << s2 << std::endl;
}

int main()
{
    std::vector<std::function<void(const char *)>> funcs;
    funcs.push_back(std::bind(&PrintStringInt, std::placeholders::_1, 4));
    funcs.push_back(std::bind(&PrintStringString, std::placeholders::_1, "bar"));
    for(auto i = funcs.begin(); i != funcs.end(); ++i){
        (*i)("foo");
    }
    return 0;
}
like image 593
user2104658 Avatar asked Feb 24 '13 15:02

user2104658


1 Answers

This is as close as I think you can get to a line by line translation, bind does not map 1:1 to any Java construct;

static void PrintStringInt(String s, int n)
{
    System.out.println(s + ", " + n);
}

static void PrintStringString(String s, String s2)
{
    System.out.println(s + ", " + s2);
}

interface MyCall {
    void fn(String value);
}

public static void main(String[] argv)
{
    Vector<MyCall> funcs = new Vector<MyCall>();
    funcs.add(new MyCall() { 
      @Override public void fn(String value) {PrintStringInt(value, 4); }});
    funcs.add(new MyCall() { 
      @Override public void fn(String value) {PrintStringString(value, "bar"); }});
    for(MyCall i : funcs){
        i.fn("foo");
    }
}
like image 154
Joachim Isaksson Avatar answered Sep 23 '22 13:09

Joachim Isaksson