這個問題在這里已經有了答案: 有沒有辦法從保存類名的字串中實體化物件? (10 個回答) 19 小時前關閉。
我有一個地圖加載功能,它使用 ifstream 從檔案中獲取輸入并從中創建物件。
以下是檔案的外觀:
tree=50,100,"assets/tree.png"
box=10,10,"assets/box.png"
它應該創建物件樹和框并將值傳遞給它們的建構式。我已經弄清楚了值部分,但我不知道如何獲取字串“tree”并創建一個樹物件。
是否可以采用字串(或 c 字串)并將其用作型別名稱?
我嘗試過的事情:
將字串作為模板型別名傳遞
#include <string> struct A {}; template<typename T> T* createType() { T* type = new T() return T; } int main() { std::string tname = "A"; auto* type = createType<tname>; }Using the using keyword
#include <string> template<std::string T> struct someType {} struct A {}; struct B {}; using someType<"A"> = A; using someType<"B"> = B; int main() { std::string tname1 = "A"; std::string tname2 = "B"; someType<tname1> typeA; someType<tname2> typeB; }
Problems:
I can't seem to find a clear answer about this but is seems like there are some problems with using a string as a template parameter.
I don't know if it is ok to pass a variable as a template parameter
I don't think that you can cast template types (from string to typename)
Is there any way that either of these, or some other way might work to accomplish this? Or is this just not possible?
uj5u.com熱心網友回復:
不。據我所知,C 中沒有規定從任何型別的語言字串中查找型別。
至于你的其他問題:
- 值模板引數必須是 constexpr:從 C 11 開始,可以使用某些 constexpr 型別的變數作為模板引數
- 顯然您可以
string_view在 C 17 中使用 constexprstring模板引數,在 C 20 中使用 constexpr 模板引數
不管這些其他答案如何,您仍然無法將這些字串轉換為型別。這種操作是典型的動態語言,但 C 是一種靜態型別的編譯語言。而且,雖然可以設計一種可以在編譯時執行這種操作的靜態語言,但這并不是 C 設計所采用的路徑。
我認為有理由問:你為什么要首先這樣做?可能有更好的方法來完成提示問題的任何內容,但如果沒有更多資訊,很難知道如何提供幫助。
編輯,以回應更新的問題:
為了從檔案中讀取資料結構,您需要自己進行字串到型別的映射。
通常,您將擁有一些“驅動程式”物件,您可以在其中注冊要從檔案創建的型別,然后在從檔案中讀取時使用這些型別。
最簡單的方法是注冊每個型別名與回呼關聯以構造資料。處理生成的異構資料結構的最直接、面向物件的方法是從一個公共Readable基類派生它們的所有型別。
注冊是您提供要在檔案中使用的型別名的地方。如果您不想在每個注冊行中重復 typename,您可以使用宏來執行此操作——例如:
#define REGISTER(type) (driver.register(#type, &(type)::construct))
(注意這#name是 C 前處理器的“字串化”語法)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/426973.html
