question on template usage

Hello,

Im a very beginner in cpp. I am trying to compile this code,

template <int K, string V>
class Entry
{
public:
Entry(const K& k, const V& v);//constructor
~Entry();
};

But it gives me,
At line 1 => 'class std::basic_string<char>' is not a valid type for a template no type parameter.
At line 5 => 'K' does not name a type.

Could someone please help ? Must be a silly mistake.
Indeed, you can't use string as a template parameter. You can only use "typename T", "class T", or integral constants.

You also can't use K as a type like that. You've defined K to be an int. K, in this context, can only be used as a integral constant, not as a generic type.

Your code is a bit strange, what are you trying to achieve here by using templates? Why not just do
1
2
3
4
5
6
class Entry
{
  public: 
    Entry(int k, const std::string& v);//constructor
    ~Entry();
};

Last edited on
Templates are used to parameterize types. An example is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using namespace std;

template <typename K, typename V>
class Entry {
    K key;
    V value;
public:
    Entry(K k, V v) : key(k), value(v) {}
    void print() { cout << key << " : " << value << '\n'; }
};

int main() {
    Entry<char, int> e1('x', 12345);
    Entry<string, int> e2("hello", 42);
    e1.print();
    e2.print();
}

Last edited on
Hi Ganado,

My bad. Thanks for your answer. I really appreciate that. By the way, its a sub class of another class where both of their member functions use these types a lot.
Thanks all. Good to know.
Topic archived. No new replies allowed.