2013-09-24 18 views
0

我目前正在爲問題定義的語言開發一個小型編譯器。你可以想象一下Lisp和Prolog的混蛋。現在,對於這種情況:在C++中爲編譯器實現符號表

Functor是3個類繼承的基類:A,B,C。

我用ANTLR3C做了一個詞法分析器和解析器,它給了我一棵AST樹。我遍歷樹,當我發現A型的功能,創建從樹中的數據類型A的對象,和sym_register對象來保存它:

#ifndef SYM_REGISTER_H 
#define SYM_REGISTER_H 

#include <vector> 
#include <string> 

enum class Symbol_type : int { T_A, T_B, T_C, T_D }; 

class sym_register { 
    public: 
     std::string name; 
     Symbol_type type; 
     std::shared_ptr<Functor> declaration; 
     std::vector <InstancedFunctor> result; 

     sym_register(std::string n, Symbol_type t, std::shared_ptr<Functor> p){ 
      name = n; type = t; declaration = p; 
     } 
}; 

#endif 

的Symbol_type枚舉類給我什麼樣的對象是std :: shared_ptr聲明的信息;指向,所以我應該能夠檢索對象的完整信息。

這是我的符號存儲在我的主要問題類:

class Problem { 
    std::map< std::string, std::shared_ptr<sym_register> > sym_table; 
}; 

我的問題是,當我嘗試從表中檢索符號,因爲我不能夠得到「宣言」屬性到它的原始類,我試過使用static_cast和reinterpret_cast沒有結果。

所以,在這裏我有各種各樣的問題:

  1. 是當我從存放指向類型A的對象上的std :: shared_ptr的喪失繼承類的「額外」的信息?
  2. 我應該去換一個開關和一個(不安全的)顯式轉換嗎?
  3. 我應該存儲指向NULL(a-la C)而不是std :: shared_ptr的指針嗎?
  4. 什麼是正確的方法來做到這一點?

編輯:基本上,我希望能夠做到:

std::shared_ptr<A> foo = Problem.getSymbol("objectWithTypeA"); 
// and so on with the rest of the class hierarchy ... 

EDIT2:編譯錯誤是:

std::shared_ptr<A> foo = it.second->declaration; 
// error: conversion from ‘std::shared_ptr<Functor>’ 
// to non-scalar type ‘std::shared_ptr<A>’ requested 

std::shared_ptr<A> foo(reinterpret_cast<std::shared_ptr<A> >(it.second->declaration)); 
// error: invalid cast from type ‘std::shared_ptr<Functor>’ 
// to type ‘std::shared_ptr<A>’ 

std::shared_ptr<A> foo(static_cast<std::shared_ptr<A> >(it.second->declaration)); 
// error: no matching function for call to ‘std::shared_ptr<A>::shared_ptr(std::shared_ptr<Functor>&)’ 
// note: candidates are: 
// long list of template instantiations with a final 
// note: no known conversion for argument 1 
// from ‘std::shared_ptr<Functor>’ to ‘const std::shared_ptr<A>&’ 

std::shared_ptr<A> foo(static_cast<A*>(it.second->declaration)); 
// error: invalid static_cast from type ‘std::shared_ptr<Functor>’ to type ‘A*’ 

std::shared_ptr<A> foo(reinterpret_cast<A*>(it.second->declaration)); 
// error: invalid cast from type ‘std::shared_ptr<Functor>’ to type ‘A*’ 
+0

你不能得到「聲明」屬性是什麼意思?是否有編譯錯誤或運行時錯誤? – molbdnilo

+0

基本上是編譯錯誤,當我嘗試將「聲明」屬性強制轉換爲其原始類別時(存儲在「type」屬性中 – CatOsMandros

+0

編譯錯誤是什麼? – filmor

回答

2

你是不是找:std::dynamic_pointer_cast<>

http://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast

std::shared_ptr<A> foo = std::dynamic_pointer_cast<A>( 
          Problem.getSymbol("objectWithTypeA")); 

Problem.getSymbol("objectWithTypeA")返回std::shared_ptr<Functor>

注意,如果對象是A類型的不返回的shared_ptr將是空的。

0

此問題的一個 「快速和骯髒」 的解決方案是做這個:

shared_ptr<A> foo = shared_ptr<A>((A *)&*it.second->declaration); 

但我覺得它應該是一個更好/更清潔/解決這個問題的更安全的解決方案(有或沒有這個特定的實現)。

+0

請不要在C++代碼中使用C-casts,而且很難搜索。 – RedX

+0

是的RedX,這是我想要避免。fjardon有我的問題的解決方案:) – CatOsMandros