gpt4 book ai didi

c++ - 模板继承 C++ 迭代器

转载 作者:行者123 更新时间:2023-11-28 02:06:43 25 4
gpt4 key购买 nike

    template<class T, template<typename> class Seq>
class SequenceWithApply : public Seq<T*>
{
public:
// 0 arguments, any type of return value:
template<class R>
void apply(R (T::*f)()) {
iterator it = begin();
while(it != end()) {
((*it)->*f)();
it++; }
}

// 1 argument, any type of return value:
template<class R, class A>
void apply(R(T::*f)(A), A a) {
iterator it = begin();
while(it != end()) {
((*it)->*f)(a);
it++; }
}

// 2 arguments, any type of return value:
template<class R, class A1, class A2>
void apply(R(T::*f)(A1, A2),
A1 a1, A2 a2) {
iterator it = begin();
while(it != end()) {
((*it)->*f)(a1, a2);
it++;
}
}
}; ///:~

//: C03:applyGromit2.cpp
// Test applyMember.h
#include "Gromit.h"
#include "applyMember.h"
#include <vector>
#include <iostream>
using namespace std;
int main() {
SequenceWithApply<Gromit, vector> dogs;
for(int i = 0; i < 5; i++)
dogs.push_back(new Gromit(i));
dogs.apply(&Gromit::speak, 1);
dogs.apply(&Gromit::eat, 2.0f);
dogs.apply(&Gromit::sleep, 'z', 3.0);
dogs.apply(&Gromit::sit);
} ///:~

我不太明白为什么编译器会在这里提示 iterator。由于这段代码实现了一个基于模板的 SequenceWithApply 类。在这种情况下,SequenceWithApply实际上是vector的基类。迭代器应该在这个基类中可见。我真的很感激有人可以帮我解决这个问题。

最佳答案

编译器寻找iterator在第一阶段查找,这是在模板被实例化之前。为了知道类派生自哪种类型,必须实例化模板(这样 Seq<T*> 就是一个实际类型)。因此,编译器永远找不到 iterator在基类中。

您可以通过两种简单的方式解决这个问题:

一次性:

typename Seq<T*>::iterator

派生类中的类型别名:

using iterator = typename Seq<T*>::iterator;

所有这些都明确指定了哪种类型 iterator属于,在第二阶段查找时查找SeqT是已知的。 More on typename .

你可以为你的函数做同样的事情:

一次性:

Seq<T*>::begin()
this->begin() // if inside a member function

using 声明:

using Seq<T*>::begin;

关于c++ - 模板继承 C++ 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37199303/

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