对于一个简单的标记分派实现,我得到了一个奇怪的函数“等于”调用,它在模板定义中不可见,也不能通过依赖于参数的查找找到。
template <typename T>
bool Equals(T lhs, T rhs){
return Equals(rhs, lhs, conditional_t<is_floating_point<T>::value, true_type, false_type>{});
}
template <typename T> // for floating
bool Equals(T lhs, T rhs, true_type){
return abs(lhs - rhs) < 0.01;
}
template <typename T> // for all the other
bool Equals(T lhs, T rhs, false_type){
return lhs == rhs;
}我做错什么了?
发布于 2021-12-18 10:20:27
在执行标记分派时,您没有实例化true_type。但更重要的是,您需要更改函数的顺序,在执行分派的函数之前需要定义标记函数,例如:
template <typename T> // for floating
bool Equals(T lhs, T rhs, true_type){
return abs(lhs - rhs) < 0.01;
}
template <typename T> // for all the other
bool Equals(T lhs, T rhs, false_type){
return lhs == rhs;
}
// moved down here!
template <typename T>
bool Equals(T lhs, T rhs){
return Equals(lhs, rhs, conditional_t<is_floating_point<T>::value, true_type{}, false_type>{});
}尽管如此,在C++17和以后的版本中,您根本不需要使用标记分发,您可以使用if constexpr代替,例如:
template <typename T>
bool Equals(T lhs, T rhs){
if constexpr (is_floating_point_v<T>)
return abs(lhs - rhs) < 0.01;
else
return lhs == rhs;
}https://stackoverflow.com/questions/70402079
复制相似问题