提问人:Gasim 提问时间:8/9/2022 更新时间:8/9/2022 访问量:157
如何衰减作为引用传递给具有可变参数的函数的常量字符?
How can I decay const char that is passed as reference to a function with variadic parameters?
问:
我有一个这样的函数:
void column(const std::string &value) { ... }
void column(float value) { ... }
template <class... TColumns> void row(const TColumns &...columns) {
ImGui::TableNextRow();
(column(columns), ...);
}
我正在使用 clang-tidy 静态分析器来确保我的代码始终符合 cpp 核心指南。我通过以下方式使用此功能:
// (const char[5], float)
row("Hello", 20.5f);
我的理解是,接受,但上面函数调用的第一个参数被推断为 .这会导致数组衰减,并且我收到 clang-tidy 错误:std:string
const char *
const char[5]
不要将数组隐式衰减为指针;请考虑改用 gsl::array_view 或显式强制转换
是否有可能以某种方式强制传递的字符串参数始终是 、 not 或 etc?const char *
const char[5]
const char[6]
答:
1赞
lorro
8/9/2022
#1
由于您每次到达此行时都会将 c 字符串转换为字符串,因此建议使用 .预计这也将解决警告问题。static string
#include <iostream>
void column(const std::string &value) { }
void column(float value) { }
template <class... TColumns> void row(const TColumns &...columns) {
// ...
(column(columns), ...);
}
int main() {
static auto hello = std::string{"Hello"};
row(hello, 20.5f);
}
然而,最好的解决方案可能是简单地关闭警告 - 无论是全局的,还是像德鲁所写的那样,通过 .// NOLINT
评论
static const std::string hello = "Hello";
string_view
column
const char[]
...template <std::size_t N> void column(const (&value)[N])
std::string
// NOLINT