簡體   English   中英

C++ 將變量分配給可能返回 void 的 function 調用

[英]C++ Assign a variable to function call that could return void

我正在嘗試編寫一個 function 來測量其他功能的執行時間。 它應該與測量的 function 具有相同的返回類型。 問題是當返回類型為void時,我得到一個編譯器錯誤Variable has incomplete type 'void' 有解決此問題的解決方法嗎? 幫助將不勝感激,謝謝!

#include <iostream>
#include <chrono>

template<class Func, typename... Parameters>
auto getTime(Func const &func, Parameters &&... args) {
    auto begin = std::chrono::system_clock::now();
    auto ret = func(std::forward<Parameters>(args)...);
    auto end = std::chrono::system_clock::now();
    std::cout << "The execution took " << std::chrono::duration<float>(end - begin).count() << " seconds.";
    return ret;
}

int a() { return 0; }
void b() {}

int main()
{
    getTime(a);
    getTime(b);
    return 0;
}

使用專業化和精心制作的歌舞套路可以解決這個問題。 但是還有一種更簡單的方法可以利用return <void expression>; 被允許。

訣竅是通過利用構造/破壞語義將其融入這個框架。

#include <iostream>
#include <chrono>

struct measure_time {

    std::chrono::time_point<std::chrono::system_clock> begin=
        std::chrono::system_clock::now();

    ~measure_time()
    {
        auto end = std::chrono::system_clock::now();
        std::cout << "The execution took "
              << std::chrono::duration<float>(end - begin).count()
              << " seconds.\n";
    }
};


template<class Func, typename... Parameters>
auto getTime(Func const &func, Parameters &&... args) {

    measure_time measure_it;

    return func(std::forward<Parameters>(args)...);
}

int a() { return 0; }
void b() {}

int main()
{
    getTime(a);
    getTime(b);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM