c++ - 不同对象类型之间的参数传递
问题描述
我想将一些参数从一个对象传输到另一个对象。对象有不同的类型。我尝试了一些方法,但都没有编译。所有类型均已给出且无法更改。
我想使用std::bind
、std::function
和std::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 );
};
解决方案
不确定这是否是您真正想要的,但是
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
.
推荐阅读
- android - Android:如何测试 android 车速表
- android - Android 调试如何在幕后工作?
- javascript - 正则表达式:如果表达式存在则匹配,但如果表达式之前有特定字符串不匹配
- mysql - 如果不同列中不存在数据,则允许重复记录
- python - 使用python在mysql表中插入JSON数组
- windows - 为什么我无法在 Windows 10 中运行的詹金斯管道中运行批处理文件?
- deployment - 制作的 TCL 程序如何部署?
- javascript - 在ngfor中交换数据后获取新数组
- compression - 如何在编写自定义 ETW 日志之前进行压缩?
- c# - 将控制台窗口输出发送到不和谐通道