首页 > 解决方案 > 声明 lambda 然后立即调用以使用其返回值初始化局部变量是否有任何目的?

问题描述

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项目。

标签: c++templateslambda

解决方案


这通常用于初始化需要为 的变量const,但初始化起来也很复杂。例如

const std::vector<int> v = [] {
   std::vector<int> vv;
   // ... very complicated logic to initialize vv
   // even could be IO, etc ...
   return vv;
}();

不这样做,就没有好的方法来制作v const.

但是,在您的情况下,在提供的示例中使用此技术的原因是,如@walnut 和@Remylebeau 所指出的,mt每次调用时都不会初始化静态变量。get_metatype


推荐阅读