这是我的容器:
std::map<std::string, Node> idents
节点和变量类:
class Node {
};
template <class T> class Variable : public Node {
public:
T value;
Variable(T arg) : value(arg) { }
~Variable();
};
我有这个功能:
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 ) );
}
}
}
编译时出现这个错误:
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 ) );
^~~~
该函数必须查看变量是否已存在(按名称),如果不存在,则将其插入 map 。变量类充当不同类型值的容器。 Node 用于创建 map ,而无需将值实例化为某些专门的变量。
最佳答案
这里有几个问题:
您正在尝试插入一个指针 (variable = new Variable<....>),而 map 不接受指针。你可能想要
std::map<std::string, Node*> idents;
反而。通过在 map 中使用指针,您还可以避免否则会面临的对象切片问题您的插入内容应类似于
idents.insert( std::pair<std::string, Node*>(name, variable ) );
(即使用节点指针并删除多余的pair
)
关于c++ - 'pair' 之前的预期主表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37769403/