有时候需要计算函数延迟, 这个时候可以做一个代理 :
before 进行 开始计数, after计数结束并计算延迟,这个时候就可以使用代理类
可以实现一个TimerProxy代理类, Invoke函数可以执行你想要计算延迟的函数, 然后在 Invoke前后加入 before 和after函数,
#pragma once #include <iostream> #include <functional> #include <string> #include <tuple> #include <memory> #include <chrono> #include <thread> inline const char* gnu_demangle(const char* raw) { while (*raw >= '0' && *raw <= '9') ++raw; // 跳过长度前缀 return raw; } inline const char* pretty_name(const char* raw) { #ifdef _MSC_VER const char* p = strrchr(raw, ' '); return p ? p + 1 : raw; // MSVC: "class Foo" → "Foo" #else // GCC/Clang return gnu_demangle(raw); // "3Foo" → "Foo" #endif } template<typename RealObject> class TimerProxy { private: std::shared_ptr<RealObject> objectPtr_; std::chrono::high_resolution_clock::time_point t1; std::chrono::high_resolution_clock::time_point t2; long long m_delay =0; public: // ✅ 完美转发构造函数 template<typename... Args> explicit TimerProxy(Args&&... args) : objectPtr_(std::make_shared<RealObject>(std::forward<Args>(args)...)) { std::string name = pretty_name(typeid(RealObject).name()); std::cout<<"name:"<< name<<std::endl; } // ✅ 从现有shared_ptr构造 explicit TimerProxy(std::shared_ptr<RealObject> ptr) : objectPtr_(std::move(ptr)) { std::string name =typeid(RealObject).name(); std::cout<<"name:"<< name<<std::endl; } void before(){ t1 = std::chrono::high_resolution_clock::now(); std::cout<<"before-------------"<<std::endl; } template<typename Func, typename... Args> decltype(auto) Invoke(Func&& func, Args&&... args) { std::cout << "Ultimate Invoke Use count: " << objectPtr_.use_count() << "\n"; before(); auto f= std::invoke( std::forward<Func>(func), *objectPtr_, // 解引用智能指针 std::forward<Args>(args)... ); after(); return f; } void after(){ t2 = std::chrono::high_resolution_clock::now(); m_delay = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count(); std::cout << "after----delay: " <<m_delay << "\n"; } long long delay() const { return m_delay; } // ✅ C++17 兼容:延迟调用 - 使用 std::tuple 代替包扩展 template<typename Func, typename... Args> auto Defer(Func&& func, Args&&... args) { std::cout << "Deferring call (C++17 compatible)\n"; // ✅ C++17 方案:使用 std::tuple 保存参数 auto tupleArgs = std::make_tuple(std::forward<Args>(args)...); // ✅ 返回延迟执行的可调用对象 return [this, func = std::forward<Func>(func), argsTuple = std::move(tupleArgs)]() mutable -> decltype(auto) { std::cout << "Executing deferred call...\n"; // ✅ 使用 std::apply 展开元组参数 return std::apply( [this, &func](auto&&... unpackedArgs) -> decltype(auto) { return std::invoke(func, *objectPtr_, std::forward<decltype(unpackedArgs)>(unpackedArgs)...); }, std::move(argsTuple) ); }; } // ✅ 条件调用:根据谓词决定是否执行 template<typename Pred, typename Func, typename... Args> decltype(auto) InvokeIf(Pred&& predicate, Func&& func, Args&&... args) { if (std::invoke(std::forward<Pred>(predicate))) { std::cout << "Condition true - invoking\n"; return std::invoke( std::forward<Func>(func), *objectPtr_, std::forward<Args>(args)... ); } else { std::cout << "Condition false - skipping\n"; // 返回默认值 using ReturnType = std::invoke_result_t<Func, RealObject&, Args...>; if constexpr (!std::is_void_v<ReturnType>) { return ReturnType{}; } } } // ✅ 批量调用:一次性执行多个操作 template<typename... Actions> void Batch(Actions&&... actions) { std::cout << "Batch execution\n"; // 使用折叠表达式执行所有操作 ((std::cout << "Executing action...\n", std::invoke(std::forward<Actions>(actions), *objectPtr_)), ...); } std::shared_ptr<RealObject> GetSharedPtr() const { return objectPtr_; } RealObject& Get() { return *objectPtr_; } const RealObject& Get() const { return *objectPtr_; } }; #ifdef _WIN32 #include <windows.h> #include <mmsystem.h> #pragma comment(lib, "winmm.lib") #endif class TestService { private: int operationCount_ = 0; public: explicit TestService() {} int ComplexOperation(int x, const std::string& op, double factor) { ++operationCount_; std::cout <<__func__ << op << " " << x << " * " << factor << "\n"; #ifdef _WIN32 timeBeginPeriod(1); Sleep(100); timeEndPeriod(1); #else std::this_thread::sleep_for(std::chrono::milliseconds(100)); #endif return static_cast<int>(x * factor); } std::string GetServiceInfo() const { return " GetServiceInfo: " + std::to_string(operationCount_); } void ResetCounter() { operationCount_ = 0; std::cout << "ResetCounter\n"; } bool IsHealthy() const { return operationCount_ > 1000; } }; int main() { TimerProxy<TestService> proxy; // ✅ 基本调用 int result1 = proxy.Invoke(&TestService::ComplexOperation, 42, std::string("Processing"), 1.5); std::cout << "Result: " << result1 << "\n\n"; // ✅ C++17 兼容的延迟调用 auto deferred = proxy.Defer(&TestService::ComplexOperation, 00, std::string("Deferred"), 2.5); std::cout << "============2=====\n"; int result2 = deferred(); std::cout << "Deferred result: " << result2 << "\n\n"; // ✅ 条件调用 int result3 = proxy.InvokeIf( [&proxy]() { return proxy.Get().IsHealthy(); }, &TestService::ComplexOperation, 200, std::string("Conditional"), 1.8 ); std::cout << "Conditional result: " << result3 << "\n\n"; // ✅ 批量调用 proxy.Batch( [](TestService& svc) { svc.ResetCounter(); }, [](TestService& svc) { svc.ComplexOperation(50, "Batch1", 1.1); } ); // ✅ 获取服务信息 std::string info = proxy.Invoke(&TestService::GetServiceInfo); std::cout << "GetServiceInfo: " << info << "\n"; return 0; }