【发布时间】:2021-11-08 17:45:02
【问题描述】:
首先我们需要做一点介绍,所以我们开始吧。我想编写一个能够检索特定类型名称的功能结构,包括模板。它会从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::tuplestd::tuple<std::vector<int>, int> -> std::tuple<:vector>, int>。所以那个元组模板的每个参数都应该调用相应的TypeName<_Ty>。
如果有不清楚的地方,请询问,因为我可能会遗漏一些东西。
【问题讨论】:
-
“由于内存原因,我决定使用
const char*而不是std::string。”我会根据原因做相反的事情...... -
您当前的
operator|写入了过去分配的内存,并泄漏了内存。 -
哦,对不起。我会使用
std::string。我认为使用const char*会更好,但事实证明并非如此(也许如果我知道如何安全地做到这一点)。