【问题标题】:Custom Types' Names Even For Templates With Variadic Arguments自定义类型的名称,即使是带有可变参数的模板
【发布时间】: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&lt;int, int&gt; -> std::tuple, std::tuple&lt;std::vector&lt;int&gt;, int&gt; -> std::tuple<:vector>, int>。所以那个元组模板的每个参数都应该调用相应的TypeName&lt;_Ty&gt;

如果有不清楚的地方,请询问,因为我可能会遗漏一些东西。

【问题讨论】:

  • “由于内存原因,我决定使用const char*而不是std::string。”我会根据原因做相反的事情......
  • 您当前的operator| 写入了过去分配的内存,并泄漏了内存。
  • 哦,对不起。我会使用std::string。我认为使用const char* 会更好,但事实证明并非如此(也许如果我知道如何安全地做到这一点)。

标签: c++ templates


【解决方案1】:

您似乎想要类似 (C++17) 的东西:

template<typename ... Ts>
struct TypeName<std::tuple<Ts...>>
{
    static inline const CString c_Name =
       (CString{ "std::tuple<" } | ... | TypeName<Ts>::c_Name) | CString{ ">" };
};

【讨论】:

  • 非常感谢。我不知道如何准确地使用那个三点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多