这个模板标题中发生了什么?
关于如何使用谷物序列化特征矩阵,有一个非常有用的答案: 使用 Cereal 库序列化 Eigen::Matrix
我复制并验证了此代码的工作原理,但我我很难理解标题中发生的事情:
template <class Archive, class _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols> inline
typename std::enable_if<traits::is_output_serializable<BinaryData<_Scalar>, Archive>::value, void>::type
save(Archive & ar, Eigen::Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> const & m)
{
int32_t rows = m.rows();
int32_t cols = m.cols();
ar(rows);
ar(cols);
ar(binary_data(m.data(), rows * cols * sizeof(_Scalar)));
}
第一行是采用谷物存档类型,然后是所有需要的特征模板参数。
我不是 100% 确定第二行在做什么,它似乎是在声明运行类型?但我无法理解这种类型的含义。
另外(如果可能,但不需要回答)
为什么这不起作用? (我没有检查过,它不会编译):
template <class Archive>
void serialize( Archive& archive, Eigen::Vector2f& vec )
{
archive(
CEREAL_NVP((float&)vec[0]),
CEREAL_NVP((float&)vec[1])
);
}
template <class Archive>
void serialize( Archive& archive, Eigen::Vector3f& vec )
{
archive(
CEREAL_NVP((float&)vec[0]),
CEREAL_NVP((float&)vec[1]),
CEREAL_NVP((float&)vec[2])
);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该模板使用 SFINAE(替换失败不是错误)来限制该函数采用的模板参数。
基本上,如果编译器认为模板函数的函数签名是错误的,它只会忽略该函数,而不是产生编译器错误。
如果
traits::is_output_serialized, Archive>::value
计算结果为true
并且会导致错误,则实际上是void
签名,如果其计算结果为false
。The template uses SFINAE (Substitution Failure Is Not An Error) to limit the template parameters this function takes.
Basically if the compiler considers the function signature of the template function to be erroneous, it simply ignores this function instead of producing a compiler error.
is effectively
void
, iftraits::is_output_serializable<BinaryData<_Scalar>, Archive>::value
evaluates totrue
and it results in an erroneous signature, if it evaluates tofalse
.