0

If I want to make the following LRU cache class templated, how do I do it? I repeatedly get the following error:

Template argument for template type parameter must be a type; did you 
forget 'typename'?"

Here's my code:

class LRU{
    int capacity;
public:
    std::list<std::pair<int, int>> doubly_queue;
    std::unordered_map<int, std::list<std::pair<int, int>>::iterator> elems;
    LRU(int c);
    int get(int key);
    void put(int key, int val);
};

LRU::LRU(int c){
   capacity = c;
}

How do I make the whole class templated?

This is the code after templating:

template<class T>
class LRU{
    int capacity;
public:
    std::list<std::pair<T, T>> doubly_queue;
    std::unordered_map<T, std::list<std::pair<T, T>>::iterator> elems;
    LRU(T c);
    int get(T key);
    void put(T key, T val);
};
Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
user3285099
  • 517
  • 1
  • 3
  • 13
  • 1
    What code do you have when you get the error? This is the non-templated code, so you should also add the templated code which gives you the error. What type are you trying to template, the key or value or both? – Tas Oct 22 '18 at 23:00

2 Answers2

1
template <typename Type>
class LRU {
    Type capacity;
public:
    std::list<std::pair<Type, Type>> doubly_queue;
    std::unordered_map<Type, typename std::list<std::pair<Type, Type>>::iterator> elems;
    LRU(Type c);
    Type get(Type key);
    void put(Type key, Type val);
};

template <typename Type>
LRU<Type>::LRU(Type c){
   capacity = c;
}

The problem was about std::list<std::pair<Type, Type>>::iterator not being a type expected as a parameter of std::unordered_map template. It's resolved using typename keyword before it. typename in this case is normally used when :: is applied to templates.

John Cvelth
  • 522
  • 1
  • 6
  • 19
1

You need to change this line:

std::unordered_map<Type, std::list<std::pair<Type, Type>>::iterator> elems;

With

std::unordered_map<Type, typename std::list<std::pair<Type, Type>>::iterator> elems;

This happens because you need to explicitly disambiguate member access syntax from nested types using typename

Jans
  • 11,064
  • 3
  • 37
  • 45