首页 > 解决方案 > 向量中的模板推导失败

问题描述

我尝试制作一个通用的叉积函数:

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 ?

标签: c++c++11

解决方案


考虑使用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]};
}

推荐阅读