Home > Mobile >  deduced class type 'Pair' in function return type
deduced class type 'Pair' in function return type

Time:03-27

I need to write a dictionary in c . I wrote a Pair class which contains 1 key value pair. I also wrote a Dictionary which contains vector pairs. I want to overload the [] operator, but it gives me an error.

template <typename TKey, typename TValue>
class Pair
{
public:
    TKey key;
    TValue value;

    Pair()
    {
        this->key = 0;
        this->value = 0;
    }

    Pair(TKey key, TValue value)
    {
        this->key = key;
        this->value = value;
    }
};

template <typename TKey, typename TValue>
class Dictionary
{
private:
    vector<Pair<TKey, TValue>> pairs;
    //...

public:
    Pair operator[] (unsigned index)
    {
        return this->pairs[index];
    }

    //...
};

The error I'm getting:

deduced class type 'Pair' in function return type

What can I do with that?

CodePudding user response:

The compiler needs to know what kind of Pair you're returning.

Pair<TKey, TValue> operator[] (unsigned index)
{
    ...
}

You may want to add a type alias to shorten the declarations:

template <typename TKey, typename TValue>
class Dictionary
{
public:
    using EntryType = Pair<TKey, TValue>;

private:
    vector<EntryType> pairs;
    //...

public:
    EntryType operator[] (unsigned index)
    {
        return this->pairs[index];
    }
};
  • Related