我目前正在爲問題定義的語言開發一個小型編譯器。你可以想象一下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沒有結果。
所以,在這裏我有各種各樣的問題:
- 是當我從存放指向類型A的對象上的std :: shared_ptr的喪失繼承類的「額外」的信息?
- 我應該去換一個開關和一個(不安全的)顯式轉換嗎?
- 我應該存儲指向NULL(a-la C)而不是std :: shared_ptr的指針嗎?
- 什麼是正確的方法來做到這一點?
編輯:基本上,我希望能夠做到:
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*’
你不能得到「聲明」屬性是什麼意思?是否有編譯錯誤或運行時錯誤? – molbdnilo
基本上是編譯錯誤,當我嘗試將「聲明」屬性強制轉換爲其原始類別時(存儲在「type」屬性中 – CatOsMandros
編譯錯誤是什麼? – filmor