jeudi 7 novembre 2019

Using C++ generic programming to do runtime call of func(x,y) for all permutations of x and y types

env->CallObjectMethod(hashMapInstance, put, _, _)

I want to call this function with all the possible permutations of std::string, int, double on the underscores. For example:

env->CallObjectMethod(hashMapInstance, put, myString, myInt)
env->CallObjectMethod(hashMapInstance, put, myInt, myDouble)
env->CallObjectMethod(hashMapInstance, put, myInt, myInt)
//...

Of course I can do this with nested ifs but I'd be reusing the same code on lots of places. Ideally I'd like a way to receive a std::map<JavaObject, JavaObject> myMap and then for each pair on the map, do the following:

for (auto pair : myMap)
    if (pair.first.type == JavaObject::String || pair.second.type == JavaObject::Integer)
        env->CallObjectMethod(hashMapInstance, put, pair.first.getString(), pair.second.getInt()) 
    //OR
    if (pair.first.type == JavaObject::Integer || pair.second.type == JavaObject::Integer)
        env->CallObjectMethod(hashMapInstance, put, pair.first.getInt(), pair.second.getInt()) //
    //OR
    if (pair.first.type == JavaObject::Double || pair.second.type == JavaObject::String)
        env->CallObjectMethod(hashMapInstance, put, pair.first.getDouble(), pair.second.getString()) 
    //...

as you can see, I need a way to efficiently be able to call each permutation env->CallObjectMethod(hashMapInstance, put, _, _) for every possible permutation of JavaObject, JavaObject received (JavaObject is just a class that can hold string, int, double and possibly more in the future)

The first thing I thought was to create a templated function:

template<typename T, typename V>
void myCallobjectMethod(env, jobject instance, jmethodID method, T obj1, V obj2)

But I still have to read JavaObject.type for the first item and then inside this if, do another if for the second part, just to call my templated function, so I'm still with the same problem.

I thought of another way, in pseudocode:

using namespace std::placeholders; 
for (auto pair : myMap)
    auto bind1 = std::bind(env->CallObjectMethod, hashMapInstance, put, _3, _4); //binds the hashMapInstance and put
    auto bind2 = std::bind(bind1, pair.first, _2); //binds the first object
    auto bind3 = std::bind(bin2, pair.second); //binds the second object
bind3(); //now I can call bind3 to execute the call 

but it's not that simple, I don't even know what's happening to the types of things here.

Aucun commentaire:

Enregistrer un commentaire