如何编写带有可选返回值的包装函数的Lambda

时间:2018-12-13 13:10:19

标签: c++ c++14 variadic-templates chrono generic-lambda

我试图编写一个lambda来度量任意函数的执行时间。在很多帮助下,我已经针对C ++ 14和具有返回值的函数进行了管理,请参见Measure execution time of arbitrary functions with C++14 lambda

然后我希望我的代码也能与C ++ 11一起工作,因此我已经使用模板函数实现了相同的想法。

最后,我意识到该代码不适用于没有返回值的函数。通用化模板函数以使时间测量对于返回void的函数也非常简单。

但是在测量lambda方面我感到困惑。编译器抱怨我要使用的可选返回值类型不完整。可以解决这个问题吗?

这是我的代码:

#include <chrono>
#include <iostream>
#include <set>

#include <boost/config.hpp>

#ifdef BOOST_NO_CXX14_GENERIC_LAMBDAS

/**
 * \brief Measures the time of arbitrary function calls.
 *
 * This template function works with C++11 and therefore it does not use
 * universal references.
 *
 * This is an internal helper template for functions returning void.
 *
 * \tparam Function function type
 * \tparam Parameters parameters type
 * \param enabled whether time measurement should be enabled
 * \param taskName name for printing the measured time
 * \param function function to measure
 * \param parameters function arguments
 *
 * \returns return value from given function
 */
template <typename Function, typename... Parameters>
auto measure(std::true_type, bool enabled,
        const std::string& taskName, Function function, Parameters... parameters) ->
        decltype(function(parameters...))
{
    std::chrono::steady_clock::time_point startTimePoint;

    if (enabled)
    {
        startTimePoint = std::chrono::steady_clock::now();
    }

    std::forward<decltype(function)>(function)(
            std::forward<decltype(parameters)>(parameters)...);

    if (enabled)
    {
        const std::chrono::steady_clock::time_point stopTimePoint =
                std::chrono::steady_clock::now();

        const std::chrono::duration<double> timeSpan =
                std::chrono::duration_cast<std::chrono::duration<double>>(
                        stopTimePoint - startTimePoint);

        std::cout << taskName << " took " << timeSpan.count() << " seconds." <<
                std::endl;
    }
}

/**
 * \brief Measures the time of arbitrary function calls.
 *
 * This template function works with C++11 and therefore it does not use
 * universal references.
 *
 * This is an internal helper template for functions returning non-void.
 *
 * \tparam Function function type
 * \tparam Parameters parameters type
 * \param enabled whether time measurement should be enabled
 * \param taskName name for printing the measured time
 * \param function function to measure
 * \param parameters function arguments
 *
 * \returns return value from given function
 */
template <typename Function, typename... Parameters>
auto measure(std::false_type, bool enabled,
        const std::string& taskName, Function function, Parameters... parameters) ->
        decltype(function(parameters...))
{
    std::chrono::steady_clock::time_point startTimePoint;

    if (enabled)
    {
        startTimePoint = std::chrono::steady_clock::now();
    }

    auto returnValue =
            std::forward<decltype(function)>(function)(
                    std::forward<decltype(parameters)>(parameters)...);

    if (enabled)
    {
        const std::chrono::steady_clock::time_point stopTimePoint =
                std::chrono::steady_clock::now();

        const std::chrono::duration<double> timeSpan =
                std::chrono::duration_cast<std::chrono::duration<double>>(
                        stopTimePoint - startTimePoint);

        std::cout << taskName << " took " << timeSpan.count() << " seconds." <<
                std::endl;
    }

    return returnValue;
}

template <typename Function, typename... Parameters>
using ReturnType = typename std::result_of<Function(Parameters...)>::type;

/**
 * \brief Measures the time of arbitrary function calls.
 *
 * This template function works with C++11 and therefore it does not use
 * universal references.
 *
 * \tparam Function function type
 * \tparam Parameters parameters type
 * \param enabled whether time measurement should be enabled
 * \param taskName name for printing the measured time
 * \param function function to measure
 * \param parameters function arguments
 *
 * \returns return value from given function
 */
template <typename Function, typename... Parameters>
auto measure(bool enabled, const std::string& taskName, Function function,
        Parameters... parameters) -> decltype(function(parameters...))
{
    return measure(std::is_void<ReturnType<Function, Parameters...>>{},
            enabled, taskName, function, parameters...);
}

#else

/**
 * \brief Measures the time of arbitrary function calls.
 *
 * This lambda works with C++14 and it accepts universal references.
 *
 * \param enabled whether time measurement should be enabled
 * \param taskName name for printing the measured time
 * \param function function to measure
 * \param parameters function arguments
 *
 * \returns return value from given function
 */
auto measure = [](bool enabled, const std::string& taskName, auto&& function,
        auto&&... parameters) -> decltype(auto)
{
    std::chrono::steady_clock::time_point startTimePoint;

    if (enabled)
    {
        startTimePoint = std::chrono::steady_clock::now();
    }

    decltype(auto) returnValue =
            std::forward<decltype(function)>(function)(
                    std::forward<decltype(parameters)>(parameters)...);

    if (enabled)
    {
        const std::chrono::steady_clock::time_point stopTimePoint =
                std::chrono::steady_clock::now();

        const std::chrono::duration<double> timeSpan =
                std::chrono::duration_cast<std::chrono::duration<double>>(
                        stopTimePoint - startTimePoint);

        std::cout << taskName << " took " << timeSpan.count() << " seconds." <<
                std::endl;
    }

    return returnValue;
};

#endif

int main(int, char**)
{
    measure(true, "Populating Ordered Set", []()
    {
        std::set<int> orderedSet;

        for (int i = 0; i < 1000; ++i)
        {
            orderedSet.insert(i);
        }
    });

 return 0;
}

如果使用C ++ 11编译器(例如带有-std = gnu ++ 11的g ++)进行编译,则它将使用模板函数,因此在这里可以很好地工作。如果使用C ++ 14编译器(-std = gnu ++ 14)进行编译,它将使用lambda,因此出现以下编译错误消息:

..\src\Main.cpp: In instantiation of '<lambda(bool, const string&, auto:1&&, auto:2&& ...)> [with auto:1 = main(int, char**)::<lambda()>; auto:2 = {}; std::__cxx11::string = std::__cxx11::basic_string<char>]':
..\src\Main.cpp:186:10:   required from here
..\src\Main.cpp:154:24: error: 'void returnValue' has incomplete type
                 decltype(auto) returnValue =
                                                ^~~~~~~~~~~    

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

  

如果使用C ++ 14编译器(-std = gnu ++ 14)进行编译,则使用lambda,因此出现此编译错误消息

让我用下面的伪代码简化您的功能

auto measure = [](someArguments....) -> decltype(auto)
{
    something1();

    decltype(auto) returnValue = somethingThatCanReturnVoid();

    something2();

    return returnValue;
};

问题是当somethingThatCanReturnVoid()返回void时,因为您无法定义void变量。

您可以使用以下事实

(1)您无法定义void变量,但可以编写return foo();,其中foo()是返回void的函数

(2)如果编写return foo(),则在执行foo()后会执行销毁该函数范围内的对象

在这一点上,解决方案似乎很明显:创建一个Bar()类型的对象,并在something2()析构函数中执行Bar

以下内容(伪代码)

auto measure = [](someArguments....) -> decltype(auto)
{
  Bar b{otherArguments...}; // something1() in contruction;
                            // something2() in destruction;

  return somethingThatCanReturnVoid();
};

这样,something1()somethingThatCanReturnVoid()之前执行,something2()在之后执行,并且编译器不会抱怨

  return somethingThatCanReturnVoid();

somethingThatCanReturnVoid()返回void时也是完全合法的

答案 1 :(得分:2)

使用RAII代替您的时间:

struct Timer
{
    explicit Timer(bool enable) : enable(enable)
    {
        if (enabled)
        {
            startTimePoint = std::chrono::steady_clock::now();
        }
    }

    ~Timer()
    {
        if (enabled)
        {
            const std::chrono::steady_clock::time_point stopTimePoint =
                    std::chrono::steady_clock::now();

            const std::chrono::duration<double> timeSpan =
                    std::chrono::duration_cast<std::chrono::duration<double>>(
                            stopTimePoint - startTimePoint);

            std::cout << taskName << " took " << timeSpan.count() << " seconds." <<
                    std::endl;
        }
    }

    Timer(const Timer&) = delete;
    Timer& operator=(const Timer&) = delete;

    bool enable;
    std::chrono::steady_clock::time_point startTimePoint;
};

然后您的函数将变为:

template <typename Function, typename... Args>
auto measure(bool enabled, const std::string& taskName, Function&& function, Args&&... args)
->  decltype(std::forward<Function>(function)(std::forward<Args>(args)...))
{
    Timer timer(enabled);

    return std::forward<Function>(function)(std::forward<Args>(args)...);
}

答案 2 :(得分:0)

使用RAII的想法可以简化模板代码。对于那些可能会觉得方便的人,我想展示一下我的最终版本:

#include <chrono>
#include <iostream>
#include <set>

#include <boost/config.hpp>

/**
 * \brief Internal timer that can be used to measure time with RAII.
 */
class InternalTimer
{
public:

    /**
     * \brief Instance creation starts the timer.
     *
     * \param enabled whether time measurement should be enabled
     * \param taskName name for printing the measured time
     */
    explicit InternalTimer(bool enabled, const std::string& taskName) :
            enabled(enabled), taskName(taskName)
    {
        if (enabled)
        {
            startTimePoint = std::chrono::steady_clock::now();
        }
    }

    /**
     * \brief Destructing the instance stops the timer and prints the measurement.
     */
    ~InternalTimer()
    {
        if (enabled)
        {
            const std::chrono::steady_clock::time_point stopTimePoint =
                    std::chrono::steady_clock::now();

            const std::chrono::duration<double> timeSpan = std::chrono::duration_cast<
                    std::chrono::duration<double>>(stopTimePoint - startTimePoint);

            std::cout << taskName << " took " << timeSpan.count() << " seconds."
                    << std::endl;
        }
    }

    /**
     * \brief Deleted copy constructor.
     */
    InternalTimer(const InternalTimer&) = delete;

    /**
     * \brief Deleted assignment operator.
     *
     * \returns reference to the object that is assigned to
     */
    InternalTimer& operator=(const InternalTimer&) = delete;

private:

    bool enabled;
    const std::string& taskName;
    std::chrono::steady_clock::time_point startTimePoint;
};

#ifdef BOOST_NO_CXX14_GENERIC_LAMBDAS

/**
 * \brief Measures the time of arbitrary function calls.
 *
 * This template function works with C++11 and therefore it does not use
 * universal references.
 *
 * \tparam Function function type
 * \tparam Parameters parameters type
 * \param enabled whether time measurement should be enabled
 * \param taskName name for printing the measured time
 * \param function function to measure
 * \param parameters function arguments
 *
 * \returns return value from given function
 */
template <typename Function, typename... Parameters>
auto measure(bool enabled, const std::string& taskName, Function function,
        Parameters... parameters) -> decltype(function(parameters...))
{
    InternalTimer timer(enabled, taskName);

    return std::forward<Function>(function)(
            std::forward<Parameters>(parameters)...);
}

#else

/**
 * \brief Measures the time of arbitrary function calls.
 *
 * This lambda works with C++14 and it accepts universal references.
 *
 * \param enabled whether time measurement should be enabled
 * \param taskName name for printing the measured time
 * \param function function to measure
 * \param parameters function arguments
 *
 * \returns return value from given function
 */
auto measure = [](bool enabled, const std::string& taskName, auto&& function,
        auto&&... parameters) -> decltype(auto)
{
    InternalTimer timer(enabled, taskName);

    return std::forward<decltype(function)>(function)(
            std::forward<decltype(parameters)>(parameters)...);
};

#endif

int main(int, char**)
{
    measure(true, "Populating Ordered Set", []()
    {
        std::set<int> orderedSet;

        for (int i = 0; i < 1000; ++i)
        {
            orderedSet.insert(i);
        }
    });

    return 0;
}