c++ - 'pair' 之前的预期主表达式

标签 c++ templates g++ stdmap std-pair

这是我的容器:

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 ,而无需将值实例化为某些专门的变量。

最佳答案

这里有几个问题:

  1. 您正在尝试插入一个指针 (variable = new Variable<....>),而 map 不接受指针。你可能想要 std::map<std::string, Node*> idents;反而。通过在 map 中使用指针,您还可以避免否则会面临的对象切片问题

  2. 您的插入内容应类似于 idents.insert( std::pair<std::string, Node*>(name, variable ) ); (即使用节点指针并删除多余的 pair )

关于c++ - 'pair' 之前的预期主表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37769403/

相关文章:

C++ << >> 运算符

c++ - g++-8 和早期版本之间的奇怪行为

python - SWIG 和 Mingw-64 与 Python 一起使用……不是有效的 Win32 应用程序

templates - 使用 require.js、主干和下划线本地化模板

Django 中的 Javascript 模板

c++ - 模板类前向声明

c++ - Makefile跨类编译

c++ - 在双菱形中到达远处基类的字段或方法的方法是什么?

java - RSA_NO_PADDING 在 Java 和 C++ 之间有什么不同?

C++ 标准化网络 TS1 和文件系统 TS