【发布时间】:2021-02-17 10:21:15
【问题描述】:
我想将一些参数从一个对象传输到另一个对象。对象有不同的类型。我尝试了一些方法,但都没有编译。所有类型均已给出且无法更改。
我想使用 std::bind、std::function、std::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