2016-03-07 75 views
0

我一直在嘗試編寫從文本輸入文件讀取並處理圖形的代碼。如何動態設置類型?

現在,圖表是模板類Graph<K, V>,其中K是節點密鑰的類型,V是節點值的類型。

比方說,我想在輸入圖形從這種格式的文本文件:

char;int // the types 
a;b;c  // the keys 
a;b,32;c,5 // edges starting from a 
b;c,2  // edges starting from b 

如何存儲類型的變量,以初始化圖形?

我願做這樣的事情:

getline(file, value, ';'); 
string keyTypeString = value; 
getline(file, value); 
string valueTypeString = value; 

type keyType = ... 
type valueType = ... 

Graph<keyType, valueType> graph = ... 

我該怎麼做,在C++?它甚至有可能嗎?

+4

C++是一種靜態類型語言,類型被設定在編譯的時候,不能在運行時改變。所以不,你想做什麼是不可能的,你必須想出另一種解決問題的方法。 –

+1

不,它不是。至少不是你想象的方式。模板實例化的類型是靜態的,在任何文件打開之前的很長時間內都會被編譯。 – StoryTeller

+0

您必須使用可以存儲不同類型的對象。看一下boost :: any – Garf365

回答

5

如果您在編譯時知道所有可能type當時的使用Boost.Variant。有很多在這個文檔的例子,但本質上,你會碰到這樣的:

using type = boost::variant<char, int>; 

std::string input; 
std::getline(file, input); 

type value; 

try { 
    value = boost::lexical_cast<int>(input); 
} catch(const boost::bad_lexical_cast&) { 
    value = input.front(); // char 
} 
0

在C++中,這是不可能的。模板是編譯時間構造。在其他語言中,相同的問題集由一個不同的結構來解決,他們稱之爲「泛型」,在運行時可能會出現這種結構,但使用C++中的模板則不然。

1

這是不可能的。 C++是一種靜態類型語言。您應該使用特定的容器來存儲任何類型的值。看看http://www.boost.org/doc/libs/1_60_0/doc/html/any.html。從提升網站

例如:

#include <list> 
#include <boost/any.hpp> 

using boost::any_cast; 
typedef std::list<boost::any> many; 

void append_int(many & values, int value) 
{ 
    boost::any to_append = value; 
    values.push_back(to_append); 
} 

void append_string(many & values, const std::string & value) 
{ 
    values.push_back(value); 
} 

void append_char_ptr(many & values, const char * value) 
{ 
    values.push_back(value); 
} 

void append_any(many & values, const boost::any & value) 
{ 
    values.push_back(value); 
} 

void append_nothing(many & values) 
{ 
    values.push_back(boost::any()); 
} 

所以你的情況,你可以有一個Graph<keyType, boost::any>圖。您應該將某個類型存儲在圖形中的某個位置。但你會使用switch case聲明在一個時刻,當你要處理的具體類型