简体   繁体   English

C++ 相当于 C99 复合文字

[英]C++ equivalent to C99 Compound Literals

I'm new to modern C++. I'm writing a serializer and need to write a single byte (a delimiter) out.我是现代 C++ 的新手。我正在编写一个序列化程序,需要写出一个字节(分隔符)。 In C99 I would use a compound literal to hold the value, something like this:在 C99 中,我会使用复合文字来保存值,如下所示:

enum {
   TAG_DELIMITER,
   // ...
   TAG_MAX
};

void write_buf(out_buf *dest, char *src, size_t n);

void encode(out_buf *buf, user_data *d) {
   // ... Write out user data
   write_buf(buf, &(char){TAG_DELIMITER}, sizeof(char));
}

In C++ the setup is similar:在 C++ 中,设置类似:

class UserData {
public:
  // ... Some data

  void encode(std::ostream &buf) {
    // ... Write out user data
    char tmp = TAG_DELIMITER;
    buf.write(&tmp, sizeof(tmp));
  }
}

Declaring a tmp variable feels clumsy.声明一个tmp变量感觉很笨拙。 This isn't a big deal, and I could just use extensions to enable compound literals if I really cared.这没什么大不了的,如果我真的很在意的话,我可以使用扩展来启用复合文字。 But is there a "C++-ish" way of doing this I'm missing?但是我缺少一种“C++-ish”的方法吗? Targeting C++20 on GCC 10.1针对 GCC 10.1 上的 C++20

EDIT: To clarify, the values from the enum are used all over the code base so I'm not going to make it into a bunch of constexprs inside a class. In any case that's just moving my tmp variable into a static class member, which really isn't any better.编辑:澄清一下,枚举中的值在整个代码库中使用,因此我不会将它变成 class 中的一堆 constexprs。无论如何,这只是将我的tmp变量移动到 static class 成员中,这真的好不到哪里去。

This question perhaps would have been better stated, "Is there a way to declare and get the address of an anonymous variable in C++?"这个问题也许会更好地表述为“有没有办法在 C++ 中声明和获取匿名变量的地址?” To which I think the answer is No.我认为答案是否定的。

In any case, the comments were right that what I really want here is just ostream.put(TAG_DELIMITER) which neatly side steps the whole question.无论如何,评论是正确的,我在这里真正想要的只是ostream.put(TAG_DELIMITER) ,它巧妙地避开了整个问题。

Youn can use constexpr :您可以使用constexpr

class UserData {
public:
    constexpr static char TAG_DELIMITER = 'a';
  // ... Some data

  void encode(std::ostream &buf) {
    // ... Write out user data
    const char * tmp = &TAG_DELIMITER;
    buf.write(tmp, sizeof(char));
  }
};

However, when you try to take its address, then you need to use const char * .但是,当您尝试获取其地址时,您需要使用const char *

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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