首先,我們需要一些介紹,所以我們開始吧。我想撰寫一個功能結構,能夠檢索特定型別的名稱,包括模板。它將從type_info或自己定義的自定義名稱回傳型別的名稱。
這是一個需要結構名稱的小型記錄器。
#define LOG(x) FunctionLog(#x, x)
template<typename _Ty>
void FunctionLog(const char* name, const _Ty& value)
{
// TypeName'll be introduced later.
std::cout << name << ": " << static_cast<const char*>(TypeName<_Ty>::c_Name) << " = " << value << '\n';
}
// Simple const char* wrapper, to easily concanate them with an operator|().
// I decided to use const char* instead of std::string due to memory.
struct CString
{
const char* Content;
explicit CString(const char* content)
: Content(content) {}
CString operator|(const CString& other)
{
return CString{ strcat(_strdup(Content), _strdup(other.Content)) };
}
operator const char*() const { return Content; }
};
template<typename _Ty>
struct TypeName
{
static inline const CString c_Name = CString{ typeid(_Ty).name() };
}
// example of implementing that struct for std::vector<_Ty>
template<typename _Ty>
struct TypeName<std::vector<_Ty>>
{
static inline const CString c_Name = CString{ "std::vector<" } | TypeName<_Ty>::c_Name | CString{ ">" };
};
我的問題是,如何使它對std::tuples起作用,因為我不知道該怎么做,因為元組有不同數量的模板引數。我希望它看起來像這樣:std::tuple<int, int>-> std::tuple<int, int>, std::tuple<std::vector<int>, int>-> std::tuple<std::vector< int>, int>。所以那個元組模板的每個引數都應該呼叫相應的TypeName<_Ty>.
如果有什么不清楚的,請問,因為我可能會錯過一些東西。
uj5u.com熱心網友回復:
看來你想要像(C 17)這樣的東西:
template<typename ... Ts>
struct TypeName<std::tuple<Ts...>>
{
static inline const CString c_Name =
(CString{ "std::tuple<" } | ... | TypeName<Ts>::c_Name) | CString{ ">" };
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/353807.html
下一篇:帶有模板未定義參考錯誤的C 繼承
