Reputation: 2917
I'm new to modern C++. I'm writing a serializer and need to write a single byte (a delimiter) out. In C99 I would use a compound literal to hold the value, something like this:
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:
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. 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? Targeting C++20 on GCC 10.1
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.
This question perhaps would have been better stated, "Is there a way to declare and get the address of an anonymous variable in 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.
Upvotes: 2
Views: 284
Reputation: 112
Youn can use 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 *
.
Upvotes: 1