【问题标题】:Using mem_fun_ref with a proxy object将 mem_fun_ref 与代理对象一起使用
【发布时间】:2012-03-29 12:44:21
【问题描述】:

我正在尝试使用 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++11 std::mem_fn 但不适用于 boost::mem_fn,但 我不能使用这两个,因为我需要指定的类型 binder 在另一个地方,生成的 binder 的类型是 未指定 boost::mem_fn。如果我可以,这将不是问题 使用decltype 但我不能因为代码需要兼容 C++03.

解决此问题的最简单方法是什么?一个习俗 mem_fun_through_proxy?

编辑:另一个警告是 proxy 类不能更改。

【问题讨论】:

  • 如果您将operator T&amp;() { return *t } 添加到您的代理会怎样?
  • @KerrekSB 啊,我忘了。也无法更改代理。其实就是一个迭代器。
  • @GeorgFritzsche 我无法控制呼叫站点,需要以通用方式调用它。
  • 你能控制什么?显然函子类型和创建?
  • @GeorgFritzsche 没错。我希望用最少的样板来完成此任务,现在有另一个函子包装器deref 执行取消引用并将结果传递给mem_fun_ref_t。不用说,这在 C++03 中是一件很脆弱的事情。

标签: c++ std c++03


【解决方案1】:

按照 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;
}

【讨论】:

    猜你喜欢
    • 2011-02-19
    • 2013-01-10
    • 2018-11-02
    • 2014-03-06
    • 2016-12-09
    • 2013-06-11
    • 2012-06-08
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多