0

我正在尝试使用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类不能改变。

4

1 回答 1

0

正如 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;
}
于 2012-04-18T21:01:20.833 回答