Mario Gil
Mario Gil

Reputation: 563

Expected primary expression before 'pair'

This is my container:

std::map<std::string, Node> idents

Node and Variable classes:

class Node {
};

template <class T> class Variable : public  Node {
public:
    T value;
    Variable(T arg) : value(arg) { }
    ~Variable();
};

And I have this function:

void assignment( const char * name, const char * val ) {
    if( identifier_exists( name ) )
        printf( "exist" );
        else {
            try { // Assume `val` is a number
                double num = std::stod( val );
                auto variable = new Variable<double>( num );
                idents.insert( std::pair<std::string, Variable<double>> pair(     std::string( name ), variable ) );
            } catch ( const std::invalid_argument& ) { // It's a string
                  auto variable = new Variable<std::string>( val );
                  idents.insert( std::pair<std::string, Variable<std::string>>  pair( std::string( name ), variable ) );
            }
        }
}

I get this error when compiling:

node.cpp:20:62: error: expected primary-expression before ‘pair’
      idents.insert( std::pair<std::string, Variable<double>> pair(   std::string( name ), variable ) );                                                             
                                                              ^~~~
node.cpp:23:67: error: expected primary-expression before ‘pair’
      idents.insert( std::pair<std::string, Variable<std::string>> pair( std::string( name ), variable ) );                                                        
                                                                   ^~~~

The function has to look if variable already exists (by name) and if not, insert it to the map. The variable class serves as a container for different types of values. Node serves to create the map without instantiating the value to some specialized Variable.

Upvotes: 0

Views: 2024

Answers (1)

jtlim
jtlim

Reputation: 4339

There are several problems here:

  1. You're trying to insert a pointer (variable = new Variable<....>) and the map doesn't take pointers. You might want std::map<std::string, Node*> idents; instead. By using pointers in the map, you also avoid the object slicing issue you would otherwise face

  2. Your insert should look like idents.insert( std::pair<std::string, Node*>(name, variable ) ); (ie. use a Node pointer and remove the extra pair)

Upvotes: 3

Related Questions