模板推导在向量中失败

Kaf*_*fka 5 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]};
}
Run Code Online (Sandbox Code Playgroud)

这条线

std::vector<double> A = cross_product(p_r2,p_r1);
Run Code Online (Sandbox Code Playgroud)

给我错误:

error : couldn't deduce template parameter ‘ReturnType’
Run Code Online (Sandbox Code Playgroud)

有没有办法保持通用性,并避免将ReturnType声明为例如double?

Sto*_*ica 8

如果容器类型遵循标准库的设计,则它们将具有value_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]};
}
Run Code Online (Sandbox Code Playgroud)


Art*_*yer 8

考虑使用类模板参数推导,并编写:

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]};
}
Run Code Online (Sandbox Code Playgroud)

或者,在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]};
}
Run Code Online (Sandbox Code Playgroud)