来自 "check if member exists using enable_if" 的修改代码无效

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

我读了这篇文章。 check if member exists using 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 << "modify\r\n";
        modifyNormal(lhs, special_());
    }

    template<typename Lhs, typename int_<decltype(Lhs::normal)>::type = 0>
    void modifyNormal(Lhs &&lhs, special_) {
        cout << "modifyNormal with normal\r\n";
    }

    template<typename Lhs>
    void modifyNormal(Lhs &&lhs, general_) {
        cout << "modifyNormal without normal\r\n";
    }
};

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;
}

但是,它只说了两次 "modifyNormal without normal"。 我错过了什么?

Lhs 在您的示例中被推断为引用类型,特别是 DataWithNormal&。引用类型没有嵌套 normal。解决这个问题的一种方法是在删除引用时检查 Lhs

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

解除 Igor 的评论,你也可以假装你有一个对象,因为即使使用引用也可以访问对象的成员:

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