英文:
Casting an enum to it's underlying type doesn't satisfy my function signature
问题
我有一个看起来像这样的函数...
```cpp
void get_u16(const char *const key, uint16_t &output) {
...这里放一些东西
}
还有一个看起来像这样的枚举...
struct MyEnum {
typedef enum : uint16_t {
FOO = 0,
BAR = 1,
} Type;
};
我试图这样调用我的函数...
MyEnum::Type thingy = MyEnum::BAR;
get_u16("一些键", (uint16_t)thingy);
它对我抱怨说...
/project/components/Data/Data.cpp:498:77: 错误: 无法将类型为 'uint16_t&' 的非常数左值引用绑定到类型为 'uint16_t' 的右值
我感到困惑。我的枚举的底层类型是 uint16_t
,而且我甚至试图在方法调用中将其转换为该类型。有没有一种方法可以告诉C++:"嗨,C++,我发誓你可以相信我。把它视为 uint16_t。" 以一种C++会遵守的方式?
<details>
<summary>英文:</summary>
I've got a function that looks like this...
void get_u16(const char *const key, uint16_t &output) {
...stuff goes here
}
And an enum that looks like this...
struct MyEnum {
typedef enum : uint16_t {
FOO = 0,
BAR = 1,
} Type;
};
And I'm trying to call my function like so...
MyEnum::Type thingy = MyEnum::BAR;
get_u16("some key", (uint16_t)thingy);
And it's complaining to me saying...
/project/components/Data/Data.cpp:498:77: error: cannot bind non-const lvalue reference of type 'uint16_t&' {aka 'short unsigned int&'} to an rvalue of type 'uint16_t' {aka 'short unsigned int'}
I'm confused. The underlying type of my enum is `uint16_t` and I'm even trying to cast it to that type in my method call. Is there some way I can say "Hey C++, I swear you can trust me. Treat this as a uint16_t." in a way where C++ will play along?
</details>
# 答案1
**得分**: 3
`(uint16_t)thingy` 是一个 *rvalue*,它是一个在完整表达式结束后就会消失的临时值。C++ 不允许将 *lvalue* 引用绑定到 rvalues。
要么你需要将参数变成 rvalue 引用:
```cpp
void get_u16(const char *const key, uint16_t &&output)
要么你需要使用常量引用:
void get_u16(const char *const key, uint16_t const &output)
要么使用一个你传递的变量:
uint16_t my_var = thingy;
get_u16("some key", my_var);
英文:
(uint16_t)thingy
is an rvalue, it's a temporary value that will disappear as soon as the full expression is finished. C++ doesn't allow you to bind lvalue references to rvalues.
Either you need to make the argument an rvalue reference:
void get_u16(const char *const key, uint16_t &&output)
Or you need to use constant references:
void get_u16(const char *const key, uint16_t const &output)
Or use a variable that you pass instead:
uint16_t my_var = thingy;
get_u16("some key", my_var);
答案2
得分: 2
(uint16_t)thingy
是一个 匿名临时对象,因此非 const
引用无法绑定到它。
void get_u16(const char *const key, const uint16_t &output) {
是一种修复方法。另一种可能性是
void get_u16(const char *const key, const uint16_t &&output) {
因为 右值引用 适合绑定。
英文:
(uint16_t)thingy
is an anonymous temporary and therefore a non-const
reference cannot bind to it.
void get_u16(const char *const key, const uint16_t &output) {
is a fix. Another possibility is
void get_u16(const char *const key, const uint16_t &&output) {
as an r-value reference is a suitable binding.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论