【问题标题】:Binder and variadic template ends up in a segmentation faultBinder 和可变参数模板最终出现分段错误
【发布时间】:2010-04-23 14:04:07
【问题描述】:

我写了以下程序

#include <iostream>
template<typename C, typename Res, typename... Args>
class bind_class_t {
private:
  Res (C::*f)(Args...);
  C *c;
public:
  bind_class_t(Res (C::*f)(Args...), C* c) : f(f), c(c) { }
  Res operator() (Args... args) {
    return (c->*f)(args...);
  }
};

template<typename C, typename Res, typename... Args>
bind_class_t<C, Res, Args...>
bind_class(Res (C::*f)(Args...), C* c) {
  return bind_class<C, Res, Args...>(f, c);
}

class test {
public:
  int add(int x, int y) {
    return x + y;
  }
};

int main() {
  test t;
  // bind_class_t<test, int, int, int> b(&test::add, &t);
  bind_class_t<test, int, int, int> b = bind_class(&test::add, &t);
  std::cout << b(1, 2) << std::endl;
  return 0;
}

用 gcc 4.3.3 编译它并得到一个分段错误。在 gdb 和这个程序上花了一些时间之后,在我看来,函数和类的地址混淆了,并且不允许调用类的数据地址。此外,如果我使用注释行代替一切正常。

其他人可以重现这种行为和/或向我解释这里出了什么问题吗?

【问题讨论】:

  • 在 C++0x 中,return {f, c}; 是允许的,所以你不需要重复长返回类型。

标签: c++ templates gcc variadic


【解决方案1】:

也许你需要

return bind_class_t<C, Res, Args...>(f, c);

而不是

return bind_class<C, Res, Args...>(f, c);

否则你会得到无穷无尽的递归。

【讨论】:

    猜你喜欢
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 2014-02-01
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    相关资源
    最近更新 更多