在 C++ 模板中发送字符串文字作为参数 - 参数包

Posted

技术标签:

【中文标题】在 C++ 模板中发送字符串文字作为参数 - 参数包【英文标题】:Send string literal as argument in C++ template - Parameter pack 【发布时间】:2020-05-30 22:31:40 【问题描述】:

我的函数声明和实现。 它接受可变数量的参数

template <typename... ParamType,
            typename = typename std::void_t<std::enable_if_t<std::is_same_v<ParamType, std::string> ||
                                                            std::is_floating_point_v<ParamType> ||
                                                            std::is_integral_v<ParamType>>...>>
static inline void Log(const ParamType &... args)

   //Implementation

我需要添加对 cstrings(char *, const char *) 和字符串文字的支持。

Console::Log("Non std::string literal"); //ERROR (const char [24])
Console::Log("hola %s %s %d %s"s,"helloWorld"s,"Joma"s,1, 1990); //OK
Console::Log<String, String, String,int, int>("hola %s %s %d %s"s,"helloWorld"s,"Joma"s,1, 1990); //OK

【问题讨论】:

只需将std::is_same_v&lt;std::decay_t&lt;ParamType&gt;, char const *&gt; 等添加到析取中即可。 错误 std::is_same_v 不满足。 那是“等”:您还需要与 char * 相同的表达式。 【参考方案1】:

关键表达式是这个析取:

std::is_same_v<ParamType, std::string> ||
std::is_floating_point_v<ParamType> ||
std::is_integral_v<ParamType>

您只需要添加这些条款:

std::is_same_v<std::decay_t<ParamType>, char const *> ||
std::is_same_v<std::decay_t<ParamType>, char *>

std::decay_t的使用会导致"abc"的类型(即char const (&amp;)[4])衰减为char const *

请注意,该函数将接收字符串字面量参数为char const (&amp;)[N],因此实现需要能够处理它。

【讨论】:

以上是关于在 C++ 模板中发送字符串文字作为参数 - 参数包的主要内容,如果未能解决你的问题,请参考以下文章

使用字符串文字作为 Django 模板中模板标签的参数

在“char 类型”模板化类中使用字符串文字

在 C++ 中是不是可以强制执行字符串文字函数参数?

如何在 js 字符串模板文字中调用带参数的函数? [关闭]

Django模板,向模板标签发送两个参数?

c++存储函数和参数列表供以后使用