为什么编译器说:'enable_if'不能用于禁用此声明
why compiler said: 'enable_if' cannot be used to disable this declaration
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> &>
': 'enable_if
'中没有名为'type
'的类型不能用于禁用此声明。"
如果我删除Edge的第二个构造函数没有错误。我想知道为什么,以及如何达到我在评论中描述的目的。
这是因为替换发生在直接上下文之外(并且失败)。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){}
相关文章:
- 用于从 ANSI 字符串转换为 std::basic_string <TCHAR>的正确函数声明
- 如何将友元声明用于具有约束的模板类
- std::enable_if 不能用于禁用此声明
- 用于移动 std::shared_ptr 的函数声明
- 模板结构的多个声明,用于获取枚举,描述模板类型
- 一旦对象设置为 null,用于声明对象的堆大小的变量就设置为 null?
- 声明适用于 auto,但不能显式声明类型?
- 为什么 puts() 不适用于声明的字符串
- 错误 C2065:'lO':用于声明向量值的未声明标识符?
- 将一个函数中声明的数组用于另一个函数
- 解决 GNU 中用于重新声明的链接器错误
- 现代C和C :可以将一个定义的结构用于其他声明的结构
- 声明具有免费功能的Unordered_set,以用于用户定义的哈希和比较
- 当整数变量用于在 c++ 中声明数组大小时,错误显示为"Expression must have a const value"
- c++amp:复合类型,用于循环,在GPU上声明
- 声明引用适用于类,但不适用于主函数
- C++警告:没有用于声明变量的链接的匿名类型
- 如何找到用于声明类的模板参数的数量?
- 用于声明具有别名的类层次结构的Cython语法
- 用于声明其他类中的对象时发生模板化类链接错误