【问题标题】:Use function pointer in template class在模板类中使用函数指针
【发布时间】:2013-06-03 21:57:06
【问题描述】:

这是我的班级精选

template <typename TValue, typename TPred = std::less<TValue> >
class BinarySearchTree {
public:
BinarySearchTree<TValue, TPred> &operator=(BinarySearchTree<TValue, TPred> const &tree) {
    if (this != &tree) {
        tree.VisitInOrder(Insert);
    }
    return *this;
}
bool Insert(TValue const &value) {
    return m_Insert(value, pRoot);
}
template <typename TVisitor> void VisitInOrder(TVisitor visitor) const;
...
};

下面的顺序不起作用:VisitInOrder(Insert) 因为我的编译器说缺少参数

但我的 main 看起来像这样,我可以在没有参数的情况下使用该函数:

void Print(int const x) { cout << x << endl; }

int main() {
    BinarySearchTree<int> obj1, obj2, obj3;
    obj1.Insert(10);
    obj1.VisitInOrder(Print);
    return 0;
}

完整代码:http://pastebin.com/TJmAgwdu

【问题讨论】:

    标签: c++ class templates


    【解决方案1】:

    你的函数Insert 是一个成员函数,这意味着它接受一个隐式的this 指针。如果你想从Insert() 中得到一元函子,你必须使用std::bind()

    if (this != &tree) {
        tree.VisitInOrder(
            std::bind(&BinarySearchTree::Insert, this, std::placeholders::_1));
    }
    

    这是一个live example,显示了当存在以下赋值时程序正在编译:

    obj3 = obj1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      相关资源
      最近更新 更多