开发者

C++ compile error with templates

开发者 https://www.devze.com 2023-03-01 02:48 出处:网络
I have this function: template <typename T> List<T>::ListNode *List<T>::find(int index) const

I have this function:

template <typename T>
List<T>::ListNode *List<T>::find(int index) const
{
    if ( (index < 1) || (index > getLength()) )
        return NULL;
    el开发者_StackOverflow社区se
    {
        ListNode *cur = head;
        for (int skip = 1; skip < index; ++skip)
            cur = cur->next;
        return cur;
    }
}

That is giving me these two errors, each on the second line:

expected constructor, destructor, or type conversion before '*' token
expected `;' before '*' token

All my other methods that use templates work just fine. I think the problem is that my syntax where I am calling my ListNode struct is wrong. I had this working without templates earlier and now I'm trying to implement it with templates and I am getting these errors.


It should be

template <typename T>
typename List<T>::ListNode *List<T>::find(int index) const
// ...

typename tells the compiler that List<T>::ListNode represents a type. When inside a template, there is a parsing ambiguity when :: is encountered. You therefore have to use the typename keyword when whatever follows :: is a type.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号