指向非静态成员变量作为模板参数的指针

Pointer to non static member variable as template parameter

本文关键字:参数 指针 静态成员 变量      更新时间:2023-10-16

看起来问题6880832对我的问题有答案,但它没有回答如何在模板化类中引用指针。我已经走到这里了:

template<typename C, typename T, T C::*m, int direction>
class Cmp {
private:
    bool isAscend = direction;
public:
    bool operator()(const C* lhs, const C* rhs) {
        return isAscend ?
            rhs->m > lhs->m :
            lhs->m > rhs->m;
    }// bool operator()(const UnRecTran* lhs,const UnRecTran* rhs)
};// class Cmp
Cmp<UnRecTran, shrtDate, &UnRecTran::date, true>

(我试图在此特定实例化中对UnRecTran::date值进行比较)。然而,我得到"'m':不是'UnRecTran'的成员"。

我想做的是可能的吗?我理解成员变量的"地址"是常量——它只是对象开始的偏移量,而不是物理(运行时)地址。

通过指向成员的指针访问成员数据的语法是:

obj.*m_ptr //obj is class type
p_obj->*m_ptr //p_obj is pointer to obj

你的操作符应该是这样的:

bool operator()(const C* lhs, const C* rhs) {
    return isAscend ?
        rhs->*m > lhs->*m :
        lhs->*m > rhs->*m;
}