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

标签 c++ templates pointers

问题 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/

相关文章:

c++ - std::max_align_t 无法打印其值

c++ - 如何在 C++ 中使用映射实现模板的返回类型查找?

grails - 我无法使grails Controller “render”方法与显式模板一起使用

c++ - 是否可以创建一个完整的 DOS 应用程序在 Windows 7 和 8 中运行

c++ - 检测传递给函数模板函数参数的特定函数

c++ - 警告 C4661 :no suitable definition provided for explicit template instantiation request

c++ - 如何将一个类中指向另一个类的指针复制到 C++ 中的另一个指针?

c++ - 这里进行了哪种显式转换?

c++ - C++对对象的引用类似于C中的双指针吗?

c++ - 带参数初始化的函数