相关疑难解决方法(0)

一种在C++中实现延迟评估的方法

所以我回答了一个关于懒惰评估的问题(这里,我的答案对于那个案例来说太过分了,但这个想法似乎很有趣),这让我想到了如何在C++中进行懒惰的评估.我提出了一个方法,但我不确定这方面的所有陷阱.是否有其他方法可以实现懒惰评估?怎么可能这样做?什么是陷阱,这个和其他设计?

这是我的想法:

#include <iostream>
#include <functional>
#include <memory>
#include <string>

#define LAZY(E) lazy<decltype((E))>{[&](){ return E; }}

template<class T>
class lazy {
private:
    typedef std::function<std::shared_ptr<T>()> thunk_type;
    mutable std::shared_ptr<thunk_type> thunk_ptr;
public:
    lazy(const std::function<T()>& x)
        : thunk_ptr(
            std::make_shared<thunk_type>([x](){
                return std::make_shared<T>(x());
            })) {}
    const T& operator()() const {
        std::shared_ptr<T> val = (*thunk_ptr)();
        *thunk_ptr = [val](){ return val; };
        return *val;
    }
    T& operator()() {
        std::shared_ptr<T> val = (*thunk_ptr)();
        *thunk_ptr = [val](){ return val; };
        return *val;
    }
};

void log(const lazy<std::string>& msg) …
Run Code Online (Sandbox Code Playgroud)

c++ lazy-evaluation c++11

13
推荐指数
2
解决办法
8415
查看次数

标签 统计

c++ ×1

c++11 ×1

lazy-evaluation ×1