我需要在雙引號內打印所有類型的字符串數據,而其他字符串數據不需要雙引號。std :: enable_if_t將字符串與非字符串函數參數分開
這是我的函數來檢查參數是否是一個字符串。
template<class T>
struct is_str : std::integral_constant<bool, false> {};
template<> struct is_str<char*> : std::integral_constant<bool, true> {};
template<> struct is_str<wchar_t*> : std::integral_constant<bool, true> {};
template<> struct is_str<const char*> : std::integral_constant<bool, true> {};
template<> struct is_str<const wchar_t*> : std::integral_constant<bool, true> {};
template<> struct is_str<std::string> : std::integral_constant<bool, true> {};
template<> struct is_str<const std::string> : std::integral_constant<bool, true> {};
template<> struct is_str<std::wstring> : std::integral_constant<bool, true> {};
template<> struct is_str<const std::wstring> : std::integral_constant<bool, true> {};
,並在打印機功能,我用這樣
template<typename T>
std::enable_if_t<is_str<T>::value>, std::ostream&>
operator<<(std::ostream& xx, const T& ar)
{
xx << "\"" << ar << "\"";
return xx;
}
template<typename T>
std::enable_if_t<!is_str<T>::value>, std::ostream&>
operator<<(std::ostream& xx, const T& ar)
{
xx << ar;
return xx;
}
上述功能它不與錯誤
編譯無法識別的模板聲明/定義
有人可以告訴我如何解決這個或更好的方式來處理噸他的情況?
請閱讀@ max66美麗的答案。他深入到代碼中的更多問題:) –