1

I have three errors:

1) 'KVList::add' : unable to match function definition to an existing declaration

2) 'KVList::replace' : unable to match function definition to an existing declaration

3) 'KVList' : use of class template requires template argument list

Here is my code

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;
}

Please help (as I have no clue how to fix these three errors as I tried everything)!

2 Answers2

3

You need to write KVList<K, V, N>& as the return type. In this context, you cannot omit the template parameters. So you would have to write:

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

and so on. However, you can omit the template parameters if you use a trailing return type.

template <class K, class V, int N>
auto KVList<K, V, N>::add(const K&, const  V&) -> KVList&
Brian Bi
  • 111,498
  • 10
  • 176
  • 312
  • I get 13 errors when I resolve these two errors...fml. unresolved external symbol :( –  Feb 16 '16 at 20:47
  • @Beelzebub You might want to read this: http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – Brian Bi Feb 16 '16 at 20:48
1

The return template object reference needs arguments:

template <class K, class V, int N> KVList<K, V, N>& KVList<K, V, N>::add(const K&, const V&) {
                                   ^^^^^^^^^^^^^^^^ 
...
}
101010
  • 41,839
  • 11
  • 94
  • 168