c++ - 将指针绑定(bind)到 C++ 中的成员运算符

标签 c++ operators

它们的意义何在?
我从来没有用过它们,而且我认为自己根本不需要使用它们。
我是不是遗漏了一些关于它们的信息,还是它们几乎没用?

编辑:我对它们了解不多,所以可能需要对它们进行描述......

最佳答案

PMF(指向成员函数的指针)类似于普通(静态)函数指针,除了因为非静态成员函数需要指定 this 对象,所以 PMF 调用语法 (.*->*) 允许指定 this 对象(在左侧)。

这是一个使用 PMF 的例子(注意使用 .* 运算符的“魔法”行:(lhs.*opit->second)(...),以及创建 PMF 的语法,&class::func):

#include <complex>
#include <iostream>
#include <map>
#include <stack>
#include <stdexcept>
#include <string>

namespace {
    using std::cin; using std::complex; using std::cout;
    using std::invalid_argument; using std::map; using std::stack;
    using std::string; using std::underflow_error;

    typedef complex<double> complexd;
    typedef complexd& (complexd::*complexd_pmf)(complexd const&);
    typedef map<char, complexd_pmf> opmap;

    template <typename T>
    typename T::reference top(T& st) {
        if (st.empty())
            throw underflow_error("Empty stack");
        return st.top();
    }
}

int
main()
{
    opmap const ops{{'+', &complexd::operator+=},
                    {'-', &complexd::operator-=},
                    {'*', &complexd::operator*=},
                    {'/', &complexd::operator/=}};

    char op;
    complexd val;
    stack<complexd> st;

    while (cin >> op) {
        opmap::const_iterator opit(ops.find(op));
        if (opit != ops.end()) {
            complexd rhs(top(st));
            st.pop();
                                        // For example of ->* syntax:
            complexd& lhs(top(st));     // complexd* lhs(&top(st));
            (lhs.*opit->second)(rhs);   // (lhs->*opit->second)(rhs);
            cout << lhs << '\n';        // cout << *lhs << '\n';
        } else if (cin.unget() && cin >> val) {
            st.push(val);
        } else {
            throw invalid_argument(string("Unknown operator ") += op);
        }
    }
}

[ Download ]

这是一个简单的 RPN 计算器,使用复数而不是实数(主要是因为 std::complex 是具有重载运算符的类类型)。我用 clang 测试过这个;您的里程可能因其他平台而异。

输入的格式应为 (0,1)。空格是可选的,但可以添加以提高可读性。

关于c++ - 将指针绑定(bind)到 C++ 中的成员运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/746604/

相关文章:

c# - 为什么 >= 有效而 => 无效?

c++ - 指针操作的未知使用

c++ - 编译Gurobi示例代码时出现链接器错误

c++ - 如何删除和删除指向存储在 vector 中的对象的指针?

c++ - 如何在 VS 2012 和 g++ 中获得 64 位长

c++ - 函数应用关联到左边

c++ - 没有赋值运算符的按位NOT运算-可能吗?

c++ - Mac 上的问题 : "Can' t find a register in class BREG while reloading asm"

c++ - 努力创建包含 std::bitset 的 Boost-Bimap

c++ - 如何求和和减去 char* 数字?