为什么编译器说:'enable_if'不能用于禁用此声明

She*_*win 6 c++ enable-if

template <bool Cond, typename Type = void>
using Enable_if = typename std::enable_if<Cond, Type>::type;

class Degree;

template <typename T>
constexpr inline bool Is_Degree() {
    return std::is_base_of<Degree, T>::value;
}

class Degree {
public:
    std::size_t inDeg = 0;
};

template <typename Satellite = Degree>
class Vertex: public Satellite {
public:
    explicit Vertex(int num): n(num) {}
private:
    std::size_t n;
};

template <typename Satellite = Degree>
class Edge {
public:
    // i want have different constructor depending on 
    // whether Vertex is (directly or indirectly) derived from Degree
    Edge(Enable_if<Is_Degree<Satellite>(), Vertex<Satellite> &>fromVertex,
        Vertex<Satellite> &toVertex)
        : from(fromVertex), to(toVertex){ ++to.inDeg; }
    Edge(Enable_if<!Is_Degree<Satellite>(), Vertex<Satellite> &>fromVertex, 
        Vertex<Satellite> &toVertex)
        : from(fromVertex), to(toVertex){}
private:
    Vertex<Satellite> &from;
    Vertex<Satellite> &to;
};
Run Code Online (Sandbox Code Playgroud)

编译器在第2行抱怨:

" 没有名为' type'in' std::__1::enable_if<false, Vertex<Degree> &>':' enable_if'的类型不能用于禁用此声明. "

如果我删除Edge的第二个构造函数,则没有错误.我想知道为什么,以及如何实现我在评论中描述的目的.

Pio*_*cki 8

这是因为替换在直接上下文之外发生(并且失败).所涉及的类型模板参数std::enable_if应该直接来自模板,当需要上下文存在函数/特化时,编译器试图实例化该模板,并且该模板在该点之前是未知的.否则,编译器可以自由拒绝您的代码.

一种可能的解决方法是将构造函数转换为模板,并将其参数默认为封闭类的模板参数的值:

template <typename S = Satellite>
//                 ^-----v
Edge(Enable_if<Is_Degree<S>(), Vertex<Satellite> &>fromVertex,
    Vertex<Satellite> &toVertex)
    : from(fromVertex), to(toVertex){ ++to.inDeg; }

template <typename S = Satellite>
//                 ^------v
Edge(Enable_if<!Is_Degree<S>(), Vertex<Satellite> &>fromVertex, 
    Vertex<Satellite> &toVertex)
    : from(fromVertex), to(toVertex){}
Run Code Online (Sandbox Code Playgroud)

DEMO