gpt4 book ai didi

c++ - 通用函数中的模板参数

转载 作者:行者123 更新时间:2023-11-30 03:02:17 25 4
gpt4 key购买 nike

我正在解决 Accelerate c++ 的练习题,这是

Implement the swap function that we used in §8.2.5/148. Why did we call swap rather than exchange the values of *beg and *end directly? Hint: Try it and see.

书上的实际功能是

template<class Bi> void reverse(Bi begin, Bi end) {
while (begin != end) {
--end;
if (begin != end)
swap(*begin++, *end);
} }

我改成了这个

template<class Bi,class X> 
void reverse(Bi b, Bi e)
{
X tmp;
while (b!= e) {
--e;
if (b != e)
{
tmp=*b;
*b=*a;
*a=tmp;
--b;
}
}
}

它没有工作,给出了以下错误。

no matching function for call to reverse(std::vector::iterator,std::vector::iterator)'

比我变成这个

template<class Bi,class X> 
void reverse(Bi b, Bi e,X c)
{
X tmp=c;
while (b!= e) {
--e;
if (b != e)
{
tmp=*b;
*b=*a;
*a=tmp;
--b;
}
}
}

并调用上面的函数作为

reverse(v.begin(),v.end(),0);

它成功了,但我仍然不明白为什么第二个不起作用?

最佳答案

编译器无法推断出您代码中的X 是什么。但是不需要为迭代器中包含的数据类型指定额外的模板类型。 std::iterator 包含一个名为 value_type 的 typedef,它正是用于此目的:

template<class Bi> 
void reverse(Bi b, Bi e)
{
typename Bi::value_type tmp;
while (b!= e) {
--e;
if (b != e)
{
tmp=*b;
*b=*a;
*a=tmp;
--b;
}
}
}

关于c++ - 通用函数中的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10269318/

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