c++ - 模板类返回类型?这是怎么写的?

标签 c++ templates

我有两个模板类,第一个是:

template <typename T>
class LL_iterator
{...}; 

和:

template <class T>
class LL
{...}

现在,问题是我正在尝试在具有“LL_iterator”返回类型的“LL”类中编写一个函数声明。 “LL”类中的函数如下所示:

LL_iterator<T> begin();

我收到的错误如下:

Error   1   error C2143: syntax error : missing ';' before '<'  c:\users\vismark1994\documents\visual studio 2013\projects\project 4\project 4\ll.h 103 1   Project 4

Error   2   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   c:\users\vismark1994\documents\visual studio 2013\projects\project 4\project 4\ll.h 103 1   Project 4

Error   3   error C2238: unexpected token(s) preceding ';'  c:\users\vismark1994\documents\visual studio 2013\projects\project 4\project 4\ll.h 103 1   Project 4

Error   4   error C1903: unable to recover from previous error(s); stopping compilation c:\users\vismark1994\documents\visual studio 2013\projects\project 4\project 4\ll.h 103 1   Project 4

下面是完整的类声明:

template <class T>
class LL
{
private:
    int count;
    Node<T>* head;
    Node<T>* tail;
    void copyList(const LL<T> &listToCopy);

public:
    LL();
    LL(const LL<T> &otherLL);
    ~LL();
    void push_back(T);
    void push_front(T);
    void pop_back();
    void clear();
    int size() const;
    T& at(int ndx);
    T& operator[] (int ndx);
    T& at(int ndx) const;
    T& operator[] (int ndx) const;
    const LL& operator=(const LL<T> & rhsObj);

    LL_iterator<T> begin();  // <-- this is where problem is 
};

template <typename T>
class LL_iterator
{

private:
    Node<T> *current;

public:
    LL_iterator();
    LL_iterator(Node<T> *ptr);
    T& operator*(); 
    LL_iterator operator++(); 
    bool operator==(const LL_iterator &rhsObj) const;
    bool operator!=(const LL_iterator &rhsObj) const;

}; //END class LL_iterator

我只是不确定如何为这样的函数(返回模板类型的函数)编写函数声明。

提前致谢!

最佳答案

您可以声明一个类模板而不定义它,就像您可以使用类、函数和变量一样:

template <typename> class Bar;

template <typename T> class Foo
{
    inline Bar<T> DoSomething();   // "inline" now has to be explicit
};

template <typename T> class Bar
{
    Foo<T> DoAnotherThing()        // implicitly "inline"
    {
        // implementation, may use Foo<T> as complete
    }
};

template <typename T>
Bar<T> Foo<T>::DoSomething()
{
   // implementation, now Bar<T> is complete, too
}

这样你就可以完成相互依赖的类模板的定义(因为成员函数返回和参数类型不需要在成员函数声明时完成),你可以在以后添加成员函数定义。

关于c++ - 模板类返回类型?这是怎么写的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29336157/

相关文章:

python - 在 C++ 中使用加载的 tensorflow 模型运行推理

c++ - 在c++源代码中调用g++

c++ - 在 Visual Studio 2010 C++ 中包含命名空间

c++ - 如何在类型依赖于派生类的基模板类中声明成员?

templates - Golang setCookie() 在模板 Execute() 之后失败

c++ - 这是什么模板?

c++ - 像 C++ 功能那样的侵入式反射?

c++ - 为什么有两个嵌套的花括号中间没有任何语句?

c++ - 为什么模板类的静态成员不是唯一的

c++ - CRTP编译错误