首页 > 解决方案 > 不同对象类型之间的参数传递

问题描述

我想将一些参数从一个对象传输到另一个对象。对象有不同的类型。我尝试了一些方法,但都没有编译。所有类型均已给出且无法更改。

我想使用std::bindstd::functionstd::mem_fn/或 lambdas。但我没有找到这些的正确混合。

有没有办法写一个模板函数来做到这一点?

(视觉工作室 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 );
};

标签: c++templatesc++14std-function

解决方案


不确定这是否是您真正想要的,但是

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);
    }
}

用法类似于

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

演示

注意:我删除了int index = 0.


推荐阅读