在C#中我可以寫這樣的事:如何獲得任何類型的默認值
class AnyThing<T>
{
static public T Default = default(T);
}
static void Main()
{
int i = AnyThing<int>.Default;
Console.WriteLine (i==0);
string s = AnyThing<string>.Default;
Console.WriteLine (s == null);
}
我打算寫像在C++模板類一本字典,我想的字典返回默認如果找不到給定的鍵,則返回通用TVal類型的值(零出)。在C#中,默認的(T)構造來拯救,而在C++中,我不確定什麼是做同樣事情的適當方式。
我試過T obj = {}
和T* obj = {}
與gcc4.7,它運作良好。我只是不太確定它是否是語言規範定義的語法,如果這種代碼是可移植的交叉編譯器和平臺。請幫助我與我的doudt!提前致謝!
PS:
~~~~~~~~~~
爲了確保模板得到任何類型的默認的(零出)值,即使那些不具有可贖回默認的構造函數,我採用以下機制(由avakar的回答啓發):
template<class T>
struct AnyThing
{
static const T& Default ;
private:
static const char temp[sizeof(T)];
};
template<class T> const char AnyThing<T>::temp[] = {};
template<class T> const T& AnyThing<T>::Default = *(T*)temp;
struct st
{
double data;
st()=delete;
};
int main()
{
cout << (int)AnyThing<char*>::Default<<endl; //0
cout << AnyThing<int>::Default<<endl; //0
cout <<AnyThing<st>::Default.data<<endl; //0
}
它看起來醜陋,但應該不會造成任何麻煩,畢竟是一個歸零的對象僅僅是一個空白內存塊。我錯了嗎?
http://stackoverflow.com/questions/1962600/what-is-c-cli-equivalent-to-cs-defaultt – Khurshid
我不完全確定這是否解決了你的問題,但我認爲[Boo st.Value Initialized](http://www.boost.org/doc/libs/release/libs/utility/value_init.htm)試圖解決這個問題。 –