问题 6880832 pointer-to-class-member-as-template-parameter 似乎回答了我的问题,但它没有回答如何在模板类中引用指针。我已经走到这一步了:
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 值进行比较)。但是,我得到“'':不是'UnRecTran'的成员”。
我正在尝试做的事情是否可行?我知道成员变量的“地址”是常量 - 它只是对象开头的偏移量,而不是物理(运行时)地址。
最佳答案
通过指向成员的指针访问成员数据的语法是:
obj.*m_ptr //obj is class type
p_obj->*m_ptr //p_obj is pointer to obj
您的运算符(operator)可能看起来像这样:
bool operator()(const C* lhs, const C* rhs) {
return isAscend ?
rhs->*m > lhs->*m :
lhs->*m > rhs->*m;
}
关于c++ - 指向非静态成员变量的指针作为模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32504469/