在此答案中,我根據(jù)類型的is_arithmetic屬性定義一個(gè)模板:template<typename T> enable_if_t<is_arithmetic<T>::value, string> stringify(T t){ return to_string(t);}template<typename T> enable_if_t<!is_arithmetic<T>::value, string> stringify(T t){ return static_cast<ostringstream&>(ostringstream() << t).str();}dyp建議,is_arithmetic是否to_string為類型定義而不是類型的屬性作為模板選擇標(biāo)準(zhǔn)。這顯然是可取的,但我不知道一種說(shuō)法:如果std::to_string未定義,則使用ostringstream重載。聲明to_string條件很簡(jiǎn)單:template<typename T> decltype(to_string(T{})) stringify(T t){ return to_string(t);}與我無(wú)法弄清楚如何構(gòu)造的標(biāo)準(zhǔn)相反。這顯然行不通,但希望它能傳達(dá)我正在嘗試構(gòu)造的內(nèi)容:template<typename T> enable_if_t<!decltype(to_string(T{})::value, string> (T t){ return static_cast<ostringstream&>(ostringstream() << t).str();}
元編程:函數(shù)定義失敗定義了單獨(dú)的函數(shù)
函數(shù)式編程
2019-11-03 04:04:33