user2609040
user2609040

Reputation:

C++ template error from typedef

The error comes from type& AssocArray<key, value>::operator[]( key& k ) which locates outside of AssocArray. I'm confused why I get the error message:

error C2143: syntax error : missing ';' before '&'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

Edit:

I have tried these following statements:

typedef typename std::pair<key, value> type;

typedef std::pair<key, value> type; 

using type = std::pair<key, value>;

they didn't work either.

template <typename key, typename value>
class AssocArray
{
public:
    typedef typename std::pair<typename key, typename value> type;

    bool addItem(key& k, value& v);

    bool isItem(key& k);

    type& operator[] (key& k);
protected:
private:
    std::vector<type> vecData;
};

template <typename key, typename value>
type& AssocArray<key, value>::operator[]( key& k )
{
    auto iter = std::find_if(vecData.begin(), vecData.end(),
        [&](type& param)
    {
        return param.first == key;
    }
    );
    if(vecData.end() != iter)
        return *iter;

    value v;
    vecData.push_back(std::make_pair(k, v));
    return *vecData.rbegin();
}

template <typename key, typename value>
bool AssocArray<key, value>::isItem( key& k )
{
    auto iter = std::find_if(vecData.begin(), vecData.end(),
        [&](type& param)
    {
        return param.first == key;
    }
    );

    return vecData.end() != iter;
}

template <typename key, typename value>
bool AssocArray<key, value>::addItem( key& k, value& v )
{
    if(isItem(k)) return false;

    vecData.push_back(std::make_pair(k, v));
    return true;
}

Upvotes: 1

Views: 527

Answers (1)

Vaughn Cato
Vaughn Cato

Reputation: 64308

As n.m. pointed out, you need something like this:

template <typename key, typename value>
AssocArray<key,value>::type& AssocArray<key, value>::operator[]( key& k )
{
    ...

or with C++11:

template <typename key, typename value>
auto AssocArray<key, value>::operator[]( key& k ) -> type &
{
    ...

Since type is a member of the class, the name doesn't become known until you are within the context of the class, either by qualifying it or waiting until after specifying that you are defining a member of the class.

Upvotes: 1

Related Questions