【发布时间】:2016-06-24 18:46:19
【问题描述】:
我有the following code 我认为应该编译但不编译。
#include <cstdint>
typedef uint8_t testtype;
enum testenum : uint8_t {
};
void foo(uint8_t& v) {}
int main() {
testtype bar;
foo(bar);
testenum baz;
foo(baz);
return 0;
}
我收到以下错误:
prog.cpp:15:9: error: invalid initialization of non-const reference of type 'uint8_t& {aka unsigned char&}' from an rvalue of type 'uint8_t {aka unsigned char}'
foo(baz);
在我看来,这应该可行,因为一切都是相同的底层类型(uint8_t)。可以将 typedef 的变量传递给 foo 函数,但枚举(具有枚举类 uint8_t)不能。
这在我的项目中意味着我不能将所有枚举传递给单个重载函数——看起来我必须为每个可能的枚举创建一个重载。
有没有一种优雅的方式来编译它,还是我必须通过第二个变量传递枚举,我可以通过引用传递?
【问题讨论】:
-
testenum可以与uint8_t相互转换,但它们并不相同。您所看到的是转换的结果是一个不能绑定到非 const 引用的右值。
标签: c++