简体   繁体   中英

How can I decay const char that is passed as reference to a function with variadic parameters?

I have a function like this:

void column(const std::string &value) { ... }

void column(float value) { ... }

template <class... TColumns> void row(const TColumns &...columns) {
  ImGui::TableNextRow();
  (column(columns), ...);
}

I am using clang-tidy static analyzer to make sure that my code is always compliant with cpp core guidelines. I am using this function in the following way:

// (const char[5], float)
row("Hello", 20.5f);

My understanding is that, std:string accepts const char * but the first argument of the function call above gets inferred to const char[5] . This causes array decay and I get clang-tidy error that:

do not implicitly decay an array into a pointer; consider using gsl::array_view or an explicit cast instead

Is it possible to somehow enforce that string argument that is passed is always const char * , not const char[5] or const char[6] etc?

Since you anyways convert a c-string to a string each time you reach this line, it's suggested to have a static string . That is expected to solve the warning as well.

#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);
}

However, the best solution is likely to simply turn off the warning - either globally, or as Drew wrote, via // NOLINT .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM