从常量初始化char数组

Ker*_*ley 6 c++

我从这段代码开始:

void func1() {
  char tmpfile[] = "/tmp/tmpXXXXXX";
  mkstemp(tmpfile);  // Note: mkstemp modifies the char array, cannot be const
  ...
}

void func2() {
  char tmpfile[] = "/tmp/tmpXXXXXX";
  mkstemp(tmpfile);  // Note: mkstemp modifies the char array, cannot be const
  ...
}
Run Code Online (Sandbox Code Playgroud)

我想重构这个以取出共享"/tmp/tmpXXXXXX"常量.这是一个尝试:

constexpr char kTmpfile[] = "/tmp/tmpXXXXXX";

void func1() {
  char tmpfile[] = kTmpfile;
  mkstemp(tmpfile);  // Note: mkstemp modifies the char array, cannot be const
  ...
}

void func2() {
  char tmpfile[] = kTmpfile;
  mkstemp(tmpfile);  // Note: mkstemp modifies the char array, cannot be const
  ...
}
Run Code Online (Sandbox Code Playgroud)

但是,这不编译.更改tmpfile[]tmpfile[sizeof(kTmpfile)]也不起作用.

下面的确有效,但它使用的是我公司的风格指南(基于Google风格指南)不鼓励的宏.

#define TMPFILE "/tmp/tmpXXXXXX"

void func1() {
  char tmpfile[] = TMPFILE;
  mkstemp(tmpfile);  // Note: mkstemp modifies the char array, cannot be const
  ...
}

void func2() {
  char tmpfile[] = TMPFILE;
  mkstemp(tmpfile);  // Note: mkstemp modifies the char array, cannot be const
  ...
}
Run Code Online (Sandbox Code Playgroud)

有没有办法写这个"很好"?无需使用宏或硬编码的大小?或者宏是可读性和可维护性的最佳选择?

Rob*_*juk 2

您可以使用std::array一些模板魔法来确定数组大小;

#include <array>
#include <algorithm>

constexpr char kTmpfile[] = "/tmp/tmpXXXXXX";

template<typename T, size_t N>
constexpr size_t array_size(T(&)[N])
{
    return N;
}

void func1() {
  std::array<char, array_size(kTmpfile)> var;
  std::copy(std::begin(kTmpfile), std::end(kTmpfile), var.begin());

  mkstemp(var.data());
  //...
}
Run Code Online (Sandbox Code Playgroud)

要获取内部数据,可以调用std::array该函数。data()