c++ - 向量中的模板推导失败
问题描述
我尝试制作一个通用的叉积函数:
template<class ContainerType1, class ContainerType2, typename ReturnType>
std::vector<ReturnType> cross_product(const ContainerType1& a, const ContainerType2& b)
{
assert((a.size()==3)&&(b.size==3));
return {a[1]*b[2]-a[2]-b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]};
}
线
std::vector<double> A = cross_product(p_r2,p_r1);
给我错误:
error : couldn't deduce template parameter ‘ReturnType’
有没有办法保持通用性,并避免将 ReturnType 声明为例如 double ?
解决方案
考虑使用Class template argument deduction,并编写:
template<class ContainerType1, class ContainerType2>
auto cross_product(const ContainerType1& a, const ContainerType2& b)
{
assert((a.size()==3)&&(b.size()==3));
return std::vector{a[1]*b[2]-a[2]-b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]};
}
或者,在 C++ 17 之前,decltype
用于获取值的类型:
template<class ContainerType1, class ContainerType2>
auto cross_product(const ContainerType1& a, const ContainerType2& b)
-> std::vector<decltype(a[0] * b[0] - a[0] - b[0])>
{
assert((a.size()==3)&&(b.size()==3));
return {a[1]*b[2]-a[2]-b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]};
}
推荐阅读
- sorting - syncsort 将 pd 精确转换为 zdf
- python - 从第一个 Combobox 获取值并更改第二个 Combobox 的值
- html - 无法在 Chrome 中将 flexbox 子项高度设置为 100%
- c# - 具有复杂项目层次结构的 .NET DataContract 序列化程序中的高递归深度问题
- c# - 如何在我的表单中更改所有面板的背景色
- python - 比较两个文件中的 x,y,z 坐标
- java - 如何将侧输入/额外输入传递给 JdbcIO RowMapper Java
- jquery - 如何ajax请求仅每3分钟更改一次的图像src?
- reactjs - 酶无法识别 lodash.flowright
- sql - 此 SQL 查询如何返回具有相同 id_product 的结果?