【发布时间】:2019-07-12 19:48:42
【问题描述】:
我正在研究 Matrix 类的实现(在 Stroustrup 的书 TC++PL 4th ed. 中有解释),但我无法真正理解某些段落。
我找到了这段代码:
文件特征.h -> https://github.com/statslabs/matrix/blob/master/include/slab/matrix/traits.h
文件 matrix.h -> https://github.com/statslabs/matrix/blob/master/include/slab/matrix/matrix.h
在 matrix.h 中有一个带有Enable_if 的函数(和其他许多函数一样):
template<typename T, std::size_t N>
template<typename M, typename F>
Enable_if<Matrix_type<M>(), Matrix<T, N> &> Matrix<T, N>::apply(const M &m, F f) {
/// Some code...
}
我认为Enable_if 说:如果(M 是Matrix),则将应用程序的返回类型声明为Matrix<T, N>&。
然后,我想知道Matrix_type<M>() 是如何工作的,所以我转到traits.h,然后阅读:
struct substitution_failure {};
template <typename T>
struct substitution_succeeded : std::true_type {};
template <>
struct substitution_succeeded<substitution_failure> : std::false_type {};
template <typename M>
struct get_matrix_type_result {
template <typename T, size_t N, typename = Enable_if<(N >= 1)>>
static bool check(const Matrix<T, N> &m);
template <typename T, size_t N, typename = Enable_if<(N >= 1)>>
static bool check(const MatrixRef<T, N> &m);
static substitution_failure check(...);
using type = decltype(check(std::declval<M>()));
};
template <typename T>
struct has_matrix_type
: substitution_succeeded<typename get_matrix_type_result<T>::type> {};
template <typename M>
constexpr bool Has_matrix_type() {
return has_matrix_type<M>::value;
}
template <typename M>
using Matrix_type_result = typename get_matrix_type_result<M>::type;
template <typename M>
constexpr bool Matrix_type() {
return Has_matrix_type<M>();
}
前 3 个结构描述成功和失败的情况,template<> 是 substitution_succeeded 的特化,它表示:如果 substitution_succeeded 的类型是 substitution_failure,则 "return" false 否则 "return" true。
我希望我说的是正确的。
现在,get_matrix_type_result 完全不为人所知。我不明白为什么它使用可变参数函数 (check(...)),declval 和 decltype 在这段代码中做了什么,以及 check 如何返回 bool 或 substitution_failure。为什么不只是bool?
谢谢。
【问题讨论】:
标签: c++ c++11 matrix sfinae decltype