使用类模板需要模板参数列表

Use of class template requires template argument list?

本文关键字:参数 列表      更新时间:2023-10-16

我有三个错误:

1( 'KVList::add' : 无法将函数定义与现有声明匹配

2( 'KVList::replace' :无法将函数定义与现有声明匹配

3( "KVList":使用类模板需要模板参数列表

这是我的代码

KVList.h

template <class K, class V, int N>
class KVList
{
    K k[N];
    V v[N];
    size_t count;
public:
    KVList();
    size_t size() const;
    const K& key(int i) const;
    const V& value(int i) const;
    KVList& add(const K&, const V&);
    int find(const K&k) const;
    KVList& replace(int i, const K& kk, const V& vv);
};

KVList.cpp

#include "KVList.h"
template <class K, class V, int N> KVList<K, V, N>::KVList() : count(0)
{
}
template <class K, class V, int N> size_t KVList<K, V, N>::size() const 
{ 
    return count; 
}
template <class K, class V, int N> const K& KVList<K, V, N>::key(int i) const 
{ 
    return k[i];
}
template <class K, class V, int N> const V& KVList<K, V, N>::value(int i) const 
{ 
    return v[i];
}
template <class K, class V, int N> KVList& KVList<K, V, N>::add(const K&, const V&) 
{ 
    if(count<N) 
    { 
        k[count] = kk; 
        v[count] = vv;
        count++; 
    } 
    return *this;
}
template <class K, class V, int N> int KVList<K, V, N>::find(const K&k) const
{
    for(int ret = 0; ret < count; ret++)
    {
        if(kk == k[ret])
        {
            return ret;
        }
    }
    return 0;
}
template <class K, class V, int N> KVList& KVList<K, V, N>::replace(int i, const K& kk, const V& vv)
{
    if (i < count)
    {
        k[i] = kk, v[i] = vv;
    }
    return *this;
}

请帮忙(因为我不知道如何解决这三个错误,因为我尝试了一切(!

您需要将KVList<K, V, N>&编写为返回类型。在此上下文中,不能省略模板参数。所以你必须写:

template <class K, class V, int N>
KVList<K, V, N>& KVList<K, V, N>::add(const K&, const  V&)

等等。但是,如果使用尾随返回类型,则可以省略模板参数。

template <class K, class V, int N>
auto KVList<K, V, N>::add(const K&, const  V&) -> KVList&

返回模板对象引用需要参数:

template <class K, class V, int N> KVList<K, V, N>& KVList<K, V, N>::add(const K&, const V&) {
                                   ^^^^^^^^^^^^^^^^ 
...
}