quod6
quod6

Reputation: 5

deduced class type 'Pair' in function return type

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?

Upvotes: 0

Views: 3045

Answers (1)

fabian
fabian

Reputation: 82461

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

Upvotes: 3

Related Questions