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

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?

最佳答案

如果您的容器类型遵循标准库的设计,则它们将具有value_type成员别名。您可以从中推导the common type:

template<class ContainerType1, class ContainerType2>
auto cross_product(const ContainerType1& a, const ContainerType2& b) ->
    std::vector<
        typename std::common_type<
            typename ContainerType1::value_type,
            typename ContainerType2::value_type
        >::type
    >
{
    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]};
}

10-04 15:05