"check if member exists using enable_if"中修改的代码不起作用

Modified code from "check if member exists using enable_if" is not working

本文关键字:if 修改 代码 不起作用 enable check member exists using      更新时间:2023-10-16

我读了本文。检查成员是否使用enable_if存在我像这样修改了Johanness Schaub的代码。

//////////////////////////////////////////////////////////////////////////
struct NormalChecker {
    struct general_ {};
    struct special_ : general_ {};
    template<typename> struct int_ { typedef int type; };
    template<typename Lhs>
    void modify(Lhs &&lhs) {
        cout << "modifyrn";
        modifyNormal(lhs, special_());
    }
    template<typename Lhs, typename int_<decltype(Lhs::normal)>::type = 0>
    void modifyNormal(Lhs &&lhs, special_) {
        cout << "modifyNormal with normalrn";
    }
    template<typename Lhs>
    void modifyNormal(Lhs &&lhs, general_) {
        cout << "modifyNormal without normalrn";
    }
};
struct DataWithNormal {
    int normal;
};
struct DataWithoutNormal {
};
int main() {
    DataWithNormal with_normal;
    DataWithoutNormal without_normal;
    NormalChecker normalCheckerWithNormal;
    normalCheckerWithNormal.modify(with_normal);
    NormalChecker normalCheckerWithoutNormal;
    normalCheckerWithoutNormal.modify(without_normal);
    return 0;
}

,但是,它只是两次说"不正常"。我错过了什么?

Lhs被推论为示例中的参考类型,特别是 DataWithNormal&。参考类型没有嵌套的normal。解决此问题的一种方法是在剥离引用时检查Lhs

decltype(std::remove_reference<Lhs>::type::normal)

提起伊戈尔的评论,您也可以假装自己有一个对象,因为访问对象的成员即使有参考:

decltype(std::declval<Lhs>().normal)