“struct std::enable_if<false, void> 中没有名为“type”的类型

Moc*_*han 15 c++ type-traits

为什么这不起作用?

它给了我一个错误

error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
     using enable_if_t = typename enable_if<_Cond, _Tp>::type;
Run Code Online (Sandbox Code Playgroud)

这我不把getX()getY()里面struct B它的工作原理。但是,如果我将它们都放在一个结构中,则不会。

error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
     using enable_if_t = typename enable_if<_Cond, _Tp>::type;
Run Code Online (Sandbox Code Playgroud)

但是,这很好用。

#include <iostream>
#include <boost/type_traits/has_dereference.hpp>

struct A {
    A(int i) : x(i) {}
    int x;
};

template<typename T>
struct B {
    template<typename std::enable_if_t<!boost::has_dereference<T>::value> * = nullptr>
    auto getX(T t) {
        return t.x;
    }

    template<typename std::enable_if_t<boost::has_dereference<T>::value> * = nullptr>
    auto getX(T t) {
        return t->x;
    }
};

int main()
{
    A a{4};

    B<A> g;

    std::cout << g.getX(a) << std::endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

解决方案

这似乎有效:

struct B {
    template<typename T, typename std::enable_if_t<!boost::has_dereference<T>::value> * = nullptr>
    auto getX(T t) {
        return t.x;
    }

    template<typename T, typename std::enable_if_t<boost::has_dereference<T>::value> * = nullptr>
    auto getX(T t) {
        return t->x;
    }
};
Run Code Online (Sandbox Code Playgroud)