p.i.g.
p.i.g.

Reputation: 2995

Parameter transfer between different object types

I would like to transfer some parameters from one object to another. The object are of different types. I tried some ways but none of them compiled. All types are given and cannot be changed.

I wanted to use std::bind, std::function, std::mem_fn and/or lambdas. But I didn't find correct mixture of these.

Is there a way to write a template function do this?

(Visual Studio 2017)

#include <functional>

class Type1 {};
class Type2 {};
class Type3 {};

class A
{
public:
    bool getter( Type1& ) const { return true; }
    bool getter( Type2& ) const { return true; }
    bool getter( Type3&, int index = 0 ) const { return true; }
};

class B
{
public:
    bool setter( const Type1& ) { return true; }
    bool setter( const Type2& ) { return true; }
    bool setter( const Type3& ) { return true; }
    bool setter( const Type3&, int ) { return true; }
};

void test()
{
    A a;
    B b;

    // Instead of this:
    Type3 data;
    if ( a.getter( data ) )
    {
        b.setter( data );
    }

    // I need something like this (which the same as above):
    function( a, A::getter, b, B::setter );
};

Upvotes: 1

Views: 84

Answers (1)

Jarod42
Jarod42

Reputation: 217478

Not sure if it is what you really want, but

template <typename T3, typename T1, typename T2>
void function(const T1& t1, bool(T1::*getter)(T3&) const,
              T2& t2, bool(T2::*setter)(const T3&))
{
    T3 data;
    if ((t1.*getter)(data))
    {
        (t2.*setter)(data);
    }
}

With usage similar to

function<Type3>(a, &A::getter, b, &B::setter);

Demo

Note: I removed int index = 0.

Upvotes: 1

Related Questions