向量中的模板推导失败

时间:2018-12-13 09:01:24

标签: c++ c++11

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

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?

2 个答案:

答案 0 :(得分:8)

如果您的容器类型遵循标准库的设计,则它们将具有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]};
}

答案 1 :(得分:8)

考虑使用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]};
}
相关问题