gpt4 book ai didi

c++ - 具有多种类型的递归模板函数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:21:37 25 4
gpt4 key购买 nike

我正在尝试编写计算两个 vector 的标量积的函数。这是代码,它可以工作。

    template <int N> 
int scalar_product (std::vector<int>::iterator a,
std::vector<int>::iterator b) {
return (*a) * (*b) + scalar_product<N - 1>(a + 1, b + 1);
}

template <>
int scalar_product<0>(std::vector<int>::iterator a,
std::vector<int>::iterator b) {
return 0;
}

但这就是问题所在——我想用模板类型替换这个迭代器,这样函数的签名看起来就像这样

    template <typename Iterator ,int N> 
int scalar_product (Iterator a, Iterator b) {
return (*a) * (*b) + scalar_product<N - 1>(a + 1, b + 1);
}

template <typename Iterator>
int scalar_product<0>(Iterator a,
Iterator b) {
return 0;
}

但这不起作用 - 我收到编译错误 C2768:非法使用显式模板参数。这看起来很傻,但我找不到我应该改变什么来避免这个错误。

最佳答案

实际上,您不必使用类型 - 我发现它们非常麻烦,而且它们的语义也不同。您不能部分特化一个函数,但您可以重载它们并通过提供默认参数值使它们表现得像特化:

#include <type_traits>

template <typename Iterator>
int scalar_product(Iterator a, Iterator b, std::integral_constant<int, 0> = std::integral_constant<int, 0>() )
{
return 0;
}

template <int N, typename Iterator>
int scalar_product (Iterator a, Iterator b, std::integral_constant<int, N> = std::integral_constant<int, N>() )
{
return (*a) * (*b) + scalar_product(a + 1, b + 1, std::integral_constant<int, N-1>() );
}

int foo()
{
int a[] = { 1, 2, 3, 4 };
int b[] = { 1, 1, 1, 1 };
return scalar_product<4>(a, b); // returns 10
}

关于c++ - 具有多种类型的递归模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20466460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com