【问题标题】:Parameter transfer between different object types不同对象类型之间的参数传递
【发布时间】:2021-02-17 10:21:15
【问题描述】:

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

我想使用 std::bindstd::functionstd::mem_fn 和/或 lambda。但我没有找到正确的混合方式。

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

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

【问题讨论】:

  • 完全不清楚你想让function做什么。如果只是专门转一个Type3,没有明显的意义。如果您希望它处理不同的 getter/setter 对,则需要以某种方式指定哪一个。如果您希望它处理所有对,则需要枚举它们。
  • 你想让函数做什么?如果您不使用模板标签,为什么还要标记它们?而不是你想要使用的东西,为什么不专注于你需要的东西?

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


【解决方案1】:

不确定是不是你真正想要的,但是

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

Demo

注意:我删除了int index = 0

【讨论】:

  • 我想我已经尝试过了(或类似的东西)。但不幸的是,它给出了 VS2017 的错误:error C2872: 'function': ambiguous symbol note: could be 'void function(const T1 &,bool (__cdecl T1::* )(T3 &) const,T2 &,bool (__cdecl T2::* )(const T3 &))'
  • 是的,我在在线演示中看到并尝试过,但是 VS2017 不喜欢它。
  • 对不起。这是一个名称冲突。它工作正常。感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
相关资源
最近更新 更多