【发布时间】:2015-09-10 13:47:01
【问题描述】:
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;
};
编译器在第 2 行抱怨:
“'
std::__1::enable_if<false, Vertex<Degree> &>'中没有名为'type'的类型:'enable_if'不能用于禁用此声明。”
如果我删除 Edge 的第二个构造函数没有错误。我想知道为什么,以及如何达到评论中描述的目的。
【问题讨论】:
-
请注意,从 C++14 开始,您可以使用
std::enable_if_t替换您的Enable_if。
标签: c++ c++11 templates sfinae enable-if