将mem_fun_ref与代理对象一起使用
Using mem_fun_ref with a proxy object
我正在尝试使用std::mem_fun_ref
(是的,不推荐使用版本原因如下)通过代理调用成员函数。
template<typename T>
struct proxy {
T& operator*() { return *t; }
T* operator->() { return t; }
// no address of etc
T* t;
};
struct A {void foo() {}};
int main()
{
A a;
proxy<A> pa = {&a};
std::mem_fun_ref_t<void, A>
fn = std::mem_fun_ref(&A::foo);
fn(pa); // borks
return 0;
}
这适用于C++11std::mem_fn
,但不适用于boost::mem_fn
,但是我不能使用这两者,因为我需要指定粘合剂在另一个地方,得到的粘合剂的类型是未指定用于boost::mem_fn
。如果我能的话,这不会是个问题使用decltype
,但我不能,因为代码需要与兼容C++03.
解决这个问题最简单的方法是什么?一种习俗mem_fun_through_proxy
?
编辑:另一个注意事项是不能更改proxy
类。
按照Georg的建议,我实现了自己的解决方案。这是简短的版本:
// snipped solution: does not include const version and hack for void
// returns
#include <functional>
namespace mine {
template<typename Ret, typename T>
class mem_fun_ref_t : public std::unary_function<T, Ret>
{
public:
explicit
mem_fun_ref_t(Ret (T::*f)())
: f(f) { }
template<typename U>
Ret
operator()(U& u) const
{ return (*u.*f)(); }
Ret
operator()(T& t) const
{ return (t.*f)(); }
private:
Ret (T::*f)();
};
} // mine
template<typename T>
struct proxy {
T& operator*() { return *t; }
T* operator->() { return t; }
// no address of etc
T* t;
};
struct X {
int foo() {return 23;}
};
int main()
{
mine::mem_fun_ref_t<int, X> fn(&X::foo);
X x;
// normal
fn(x);
proxy<X> px = {&x};
fn(px);
return 0;
}
相关文章:
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 将 exprtk 与自定义类的对象一起使用
- 如何将来自 Boost.Python 的map_indexing_suite与自定义而不是标准对象一起使用?
- 将 std::variant 与 gmock 1.8 对象一起使用时编译错误
- 将 OpenGL 实例化图形与移动对象一起使用
- 如何使用 new 和 delete 与 OpenGL 的缓冲区对象一起使用?
- 如何将指针与对象一起使用;构造函数和破坏者.C
- 有没有一种方法可以将升压信号和插槽与不可复制的对象一起使用
- 有可能实现一个与数组而不是单个对象一起工作的内存池吗
- 如何将自由函数与对象一起使用
- 与对象一起返回时清除了内存指针
- QML:如何将动态创建的组件与自定义的内部对象一起使用
- 将对向量与用户定义的类对象一起使用
- 如何将setw与对象一起使用
- 将 forward_list::p ush_front() 与结构对象一起使用
- 在 C++ lambda 表达式中按值捕获是否需要将值与 lambda 对象一起复制
- 将mem_fun_ref与代理对象一起使用
- 如何将矢量与引用对象一起使用
- MFC:将 GetContextMenuManager()->ShowPopup 与 Office2007 视觉对象一起使用时的延迟
- 与ifsteam对象一起使用.open的问题