【问题标题】:expected primary-expression received in g++在 g++ 中收到预期的主要表达式
【发布时间】:2015-03-12 16:47:36
【问题描述】:

这段代码用 VS 编译成功,但是移植到 Linux 并用 g++ 编译时出错。

template <class Key, class  Value> 
void Dictionary<Key, Value>::set(const Key &key, Value value)
{
    typename Dictionary<Key,Value>::iterator i = this->find(key);
    if (i == this->end())   
    {
        access(&key, &value, eINSERT);
        this->insert(value_type(key, value));       
    }
    else
    {
        access(&key, &i->second, eCLEAR);
        dispose(i->second);
        access(&key, &value, eSET);
        i->second = value;
    }
}

template <class Key, class  Value> class PtrDictionary : public Dictionary<Key, Value>;

class Processor
{
    private:
        ptrdictionary<const string,const type*>         m_Types;

    void Processor::add(const string name, const Type* t)
    {
        if (m_Types.get(name))
            error("Type '"+string(name)+"' already defined", eParseError);

        m_Types.set(name, t); // this is where the error is received
    }
}

错误是:

../Packages/Dictionary.h: 在 'void Dictionary::set(const Key&, Value) [with Key = const 标准::基本字符串;值 = 常量 AsmLoader::Type*]': Instructions.cpp:94:21:从这里需要 ../Packages/Dictionary.h:79:37:错误:预期的主表达式
this->insert(value_type(key, value));

更新:

value_type 是 std::map 中的一个对象,g++ 编译代码所需要的只是添加这个:

typedef typename map<const Key, Value>::value_type value_type;

感谢大家的cmets,这是我第一次使用SO,这是一个非常复杂的代码,所以我忘了指定这部分......

【问题讨论】:

  • 你试过this-&gt;m_Types.set(name, t)
  • 我有,错误依旧...
  • 这是完整的错误吗?
  • 错误表示set() 函数中的this-&gt;insert(value_type(key, value)); 导致了问题。 value_type() 是什么?
  • @ 0x499602D2 这是完整的错误。 @NathanOliver value_type() 是来自 std::map 的类型。

标签: c++ templates compiler-errors g++


【解决方案1】:

不幸的是,它看起来不像在 VS 中可以以相同的方式实现。在研究这一点时,我发现:

Can dictionaries be used in c++

他们建议在 STL 中使用 std::map 作为 C++ 中的类似方法(没有 .NET)。如果上述链接发生变化,以下是提供的答案的引用:

在 STL 中有一个对应的类型,叫做 std::map。

它具有与 .NET 字典相同的基本功能,但 实现方式大相径庭。 std::map 在内部基于 红黑树数据结构,而 Dictionary 使用哈希表 内部。

如果您只是在寻找具有相同行为的东西,std::map 可以,但是如果您有大量数据,则必须注意 不同的性能特征。

** 警告 - 我仍在学习,如果这与您最初的问题不符,请道歉。希望这会有所帮助!

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
  • @cpburnz 我会记住这一点并更新答案 --- 非常感谢
【解决方案2】:

解决了! value_type 是 std::map 中的一个对象,g++ 编译代码所需要的只是添加这个:

typedef typename map<const Key, Value>::value_type value_type;

【讨论】:

    猜你喜欢
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多