【发布时间】:2020-04-08 20:51:25
【问题描述】:
template<typename T>
static const Metatype* get_metatype() {
static const Metatype* mt = []() {
constexpr size_t name_hash = Metatype::build_hash<T>().name_hash;
auto type = metatype_cache.find(name_hash);
if (type == metatype_cache.end()) {
constexpr Metatype newtype = Metatype::build<T>();
metatype_cache[name_hash] = newtype;
}
return &metatype_cache[name_hash];
}();
return mt;
}
由 lambda 的返回值初始化的变量 mt。为什么不直接提取 lambda 代码并使其成为 get_metatype() 函数的一部分,然后只从中返回值呢?这是一些表演技巧还是什么?
此代码来自 decs https://github.com/vblanco20-1/decs 项目,我正在学习用于教育目的。
【问题讨论】: