nxdong August 10, 2022 [cpp] #cpp
在看arrow代码的时候, 在FlatBuffer 生成的代码中有一段代码没看明白。记录一下这个用法。
代码
func_return_refarr.cpp 文件内容如下:
#include <stdio.h>
const int (&get_static_ref())[4]
{
static const int values[] = {1, 2, 3, 4};
return values;
}
typedef int int_array4[4];
const int_array4 &get_static_ref_typedef()
{
static const int values_type[] = {4, 3, 2, 1};
return values_type;
}
int main(int argc, char const *argv[])
{
const int(&arr_ref)[4] = get_static_ref();
printf("arr_ref[0]: %d arr_ref[1]: %d arr_ref[2]: %d arr_ref[3]: %d \n", arr_ref[0], arr_ref[1], arr_ref[2], arr_ref[3]);
const int_array4 &arr_ref_typedef = get_static_ref_typedef();
printf("arr_ref_typedef[0]: %d arr_ref_typedef[1]: %d arr_ref_typedef[2]: %d arr_ref_typedef[3]: %d \n", arr_ref_typedef[0], arr_ref_typedef[1], arr_ref_typedef[2], arr_ref_typedef[3]);
return 0;
}
编译&&运行
g++ func_return_refarr.cpp
./a.out
arr_ref[0]: 1 arr_ref[1]: 2 arr_ref[2]: 3 arr_ref[3]: 4
arr_ref_typedef[0]: 4 arr_ref_typedef[1]: 3 arr_ref_typedef[2]: 2 arr_ref_typedef[3]: 1
FlatBuffer 生成的代码
https://github.com/apache/arrow/blob/master/cpp/src/generated/feather_generated.h#L167
enum class TimeUnit : int8_t {
SECOND = 0,
MILLISECOND = 1,
MICROSECOND = 2,
NANOSECOND = 3,
MIN = SECOND,
MAX = NANOSECOND
};
inline const TimeUnit (&EnumValuesTimeUnit())[4] {
static const TimeUnit values[] = {TimeUnit::SECOND, TimeUnit::MILLISECOND,
TimeUnit::MICROSECOND, TimeUnit::NANOSECOND};
return values;
}
inline const char* const* EnumNamesTimeUnit() {
static const char* const names[5] = {"SECOND", "MILLISECOND", "MICROSECOND",
"NANOSECOND", nullptr};
return names;
}
inline const char* EnumNameTimeUnit(TimeUnit e) {
if (flatbuffers::IsOutRange(e, TimeUnit::SECOND, TimeUnit::NANOSECOND)) return "";
const size_t index = static_cast<size_t>(e);
return EnumNamesTimeUnit()[index];
}
参考
c-function-returning-reference-to-array