我正在嘗試在接受通用函式指標和打包引數的頭檔案中創建一個函式模板。函式模板將使用打包引數呼叫接收到的函式指標。我的目標是計算并回傳函式指標的執行時間。
#ifndef LOGTIME_HPP
#define LOGTIME_HPP
#include <chrono>
#include <ratio>
template<typename Function, typename... Args>
double getExecutionTime(Function&& function, Args&&... args) {
auto t1 = std::chrono::high_resolution_clock::now();
std::invoke(std::forward<Function>(function), std::forward<Args>(args)...);
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> ms = t2 - t1;
return ms.count();
}
#endif
這似乎只適用于不是 aclass或 的成員函式的函式指標struct。這是使用函式模板的一些示例代碼:
#include <iostream>
#include <thread>
#include <random>
#include "LogTime.hpp" // header including getExecutionTime()
class Obj
{
public:
int testFunc(int dur, int num) {
std::cout << "test" << num;
for (int i = 0; i < dur; i ) {
std::cout << ".";
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return 2;
}
};
int testFunc(int dur, int num) {
std::cout << "test" << num;
for (int i = 0; i < dur; i ) {
std::cout << ".";
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return 1;
}
int main()
{
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<> uniform_dist(1, 100);
Obj obj = Obj();
for (int i = 0; i < 10; i ) {
int rand = uniform_dist(rng);
std::cout << "elapsed: "
// this works
<< getExecutionTime(testFunc, uniform_dist(rng), i) << std::endl;
// this doesn't work
<< getExecutionTime(Obj::testFunc, uniform_dist(rng), i) << std::endl;
}
}
我的問題Obj::testFunc是失敗了。我知道如果Obj::testFunc是靜態的,那么該函式會執行得很好。我讀過std::invoke可以通過傳遞型別別的實體來呼叫成員函式。但是,我不知道如何將其合并到函式模板中(我以前從未使用過模板)。
I would appreciate any help or insight.
uj5u.com熱心網友回復:
非靜態成員函式有一個型別別的隱式引數作為函式的第一個引數,它是映射到this指標的物件。這意味著您需要將型別別的物件作為成員函式指標之后的第一個引數傳遞,例如
<< getExecutionTime(&Obj::testFunc, obj, uniform_dist(rng), i) << std::endl;
或者您可以使用 lambda 代替
<< getExecutionTime([&](){ obj.testFunc(uniform_dist(rng), i); }) << std::endl;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/333137.html
標籤:c templates function-pointers function-templates
上一篇:使用奇怪重復模板模式(CRTP)時計算多維陣列的線性索引
下一篇:如何根據回傳型別推匯出模板引數?
