C ++中的Python样式装饰器17

问题描述 投票:2回答:1

我正在使用最新的C ++技术制作像装饰器一样的python。我已经在这里看到了一些解决方案(Python-like C++ decorators),但我想知道它是否可以做得更好。在其他人的帮助下(Constructing std::function argument from lambda),我提出了以下解决方案。

template<typename TWrapped>
auto DurationAssertDecorator(const std::chrono::high_resolution_clock::duration& maxDuration, TWrapped&& wrapped)
{
    return [wrapped = std::forward<TWrapped>(wrapped), maxDuration](auto&&... args)
    {
        const auto startTimePoint = std::chrono::high_resolution_clock::now();

        static_assert(std::is_invocable<TWrapped, decltype(args)...>::value, "Wrapped object must be invocable");

        if constexpr (!(std::is_void<decltype(wrapped(std::forward<decltype(args)>(args)...))>::value))
        {
            // return by reference will be here not converted to return by value?
            //auto result = wrapped(std::forward<decltype(args)>(args)...);

            decltype(wrapped(std::forward<decltype(args)>(args)...)) result = wrapped(std::forward<decltype(args)>(args)...);

            const auto endTimePoint = std::chrono::high_resolution_clock::now();
            const auto callDuration = endTimePoint - startTimePoint;
            assert(callDuration <= maxDuration);

            return result;
        }
        else
        {
            wrapped(std::forward<decltype(args)>(args)...);

            const auto endTimePoint = std::chrono::high_resolution_clock::now();
            const auto callDuration = endTimePoint - startTimePoint;
            assert(callDuration <= maxDuration);
        }
    };
}

我不会故意使用下面的“auto”来确保返回类型是我期望的(或至少是兼容的)。

我将能够使用任何可调用的:无状态lambda,statefull lambda,struct functor,函数指针,std :: function

std::function<double(double)> decorated = DurationAssertDecorator(1s, [](const double temperature) { return temperature + 5.0; });
double a = decorated (4);

组成也应该没问题:

std::function<double()> wrapped = LogDecorator(logger, [] { return 4.0; });
std::function<double()> wrapped_wrapped = DurationAssertDecorator(1s, functor);

这应该不行 - int literal 5不是可调用的:

std::function<void(double)> decorated = DurationAssertDecorator(1s, 5);

到目前为止它确实可以解决问题:

  • 案例 - 包装函数有一个返回值 - 我不确定我是否只是通过auto得到结果,包装的返回值是一个引用。如果是这样,那么将发生一个副本而不是保持引用(通过指针返回和按值返回)。所以这就是为什么我想出那个奇怪的结构。我可以做得更好吗?
  • 还有哪些其他改进/修复可能?
c++ lambda stl c++17
1个回答
0
投票

我已经意识到,如果我使用RAII对象进行呼叫前和呼叫后活动,我可以更加简化代码。不再需要void和非void返回值处理。

template<typename TWrapped>
auto DurationAssertDecorator(const std::chrono::high_resolution_clock::duration& maxDuration, TWrapped&& wrapped)
{
    return [wrapped = std::forward<TWrapped>(wrapped), maxDuration](auto&&... args) mutable
    {
        static_assert(std::is_invocable<TWrapped, decltype(args)...>::value, "Wrapped object must be invocable");

        struct Aspect
        {
            // Precall logic goes into the constructor
            Aspect(const std::chrono::high_resolution_clock::duration& maxDuration)
                : _startTimePoint(std::chrono::high_resolution_clock::now())
                , _maxDuration(maxDuration)
            {}

            // Postcall logic goes into the destructor
            ~Aspect()
            {
                const auto endTimePoint = std::chrono::high_resolution_clock::now();
                const auto callDuration = endTimePoint - _startTimePoint;
                assert(callDuration <= _maxDuration);
            }

            const std::chrono::high_resolution_clock::time_point _startTimePoint;
            const std::chrono::high_resolution_clock::duration& _maxDuration;
        } aspect(maxDuration);

        return wrapped(std::forward<decltype(args)>(args)...);
    };
}

它适用于正常的用例:

auto wrappedFunctor = DurationAssertDecorator(1s, [](const double temperature)  { return temperature; });

我也希望使用非const仿函数,比如mutable lambdas:

auto wrappedFunctor = DurationAssertDecorator(1s, 
    [firstCall = true](const double temperature) mutable
    {
        if (firstCall)
        {
            firstCall = false;
            return temperature;
        }
        std::this_thread::sleep_for(2s);
        return temperature;
    });

所以我很满意这个解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.