Domanda

I have a function layout like the following one:

bool foo( object1, object2, method_x, op_y, method_z ) {
    if (object1.method_x() op_y object2.method_z()) {
        do something;
}

The objects object1 and object2 are always from the same class. But their methods and the operators in between are arbitrary. I know you can pass an operator as a template parameter and this would do the job. But what about the member functions? They take no arguments if that helps.

È stato utile?

Soluzione

If you're looking to avoid typing, MACROs are the usual (evil) mechanism here.

In C++1y you could use polymorphic lambdas to achieve something similar.

foo(object1, object2, 
      [](auto o) { return o.method_x(); }, 
      [](auto a, auto b) { return a == b }, 
      [](auto o) { return o.method_z() });

Of course as long as the methods are just that, you could

foo(object1, object2, 
      std::memfn(&Object1::method_x),
      [](auto a, auto b) { return a == b }, 
      std::memfn(&Object2::method_z));

Update: since you added that types can be restricted, you could replace all the auto with the appropriate type and maybe use

template <typename T, typename Mx, typename Op, typename Mz>
bool foo(T& object1, T& object2, Mx method_x, Op op_y, Mz method_z ) {
    if (op_y(method_x(object1), method_z(object2)) {
        // do something;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top