我需要一個std :: bind函數包裝器,它將在包裝函數之前調用,並將參數傳遞給包裝函數。在C++中爲std :: bind函數裝飾器0x
std::function<void (int)> foo = postbind<int>(service, handle);
我這麼遠下來到
std::function<void (int)> foo = postbind(service, handle);
我如何刪除模板參數?它似乎歸結爲從對象生成函數(postbind)中扣除的類型不夠智能。
#include <functional>
template<typename T>
void foo(std::function<void (T)> func)
{
}
void handler(int x)
{
}
int main()
{
foo(handler);
return 0;
}
說錯誤:調用 '富(無效(&)(INT))'
沒有匹配的功能然而,代碼示例:
template<typename T>
void foo(T t)
{
}
int main()
{
foo(99);
return 0;
}
這工作。任何想法如何使這項工作?我需要能夠將std :: bind傳遞給它,並將結果成功轉換爲std :: function。
如何刪除模板參數?謝謝。
問:什麼是服務,這個班意味着什麼? A.將封裝了boost :: asio :: io_service->的函數封裝封裝到當前線程之外。
全部源代碼:
#include <iostream>
#include <functional>
#include <memory>
class io_service
{
};
typedef std::shared_ptr<io_service> service_ptr;
template <typename Arg1>
class postbind_impl_1
{
public:
typedef std::function<void (Arg1)> function;
postbind_impl_1(service_ptr service, function memfunc)
: service_(service), memfunc_(memfunc)
{
}
void operator()(Arg1 arg1)
{
// do stuff using io_service
memfunc_(arg1);
}
private:
service_ptr service_;
function memfunc_;
};
template <typename Arg1>
postbind_impl_1<Arg1> postbind(service_ptr service,
typename postbind_impl_1<Arg1>::function handle)
{
return postbind_impl_1<Arg1>(service, handle);
}
// ----------------
void handle(int x)
{
std::cout << x << "\n";
}
int main()
{
service_ptr service;
std::function<void (int)> foo = postbind(service, handle);
foo(110);
return 0;
}
什麼是'service'和'handle'?你能舉一個預期用法的例子嗎? –
在上面解答了您的問題。 ATM我使用std :: bind函數將一個函數傳遞給一個操作,該操作在完成後調用句柄(...)(即handle_connect)。如果handle_connect是在單獨線程中運行的api的一部分,那麼我在內部需要將handle_connect發佈到do_handle_connect以便切換線程 - 醜陋。我寧願有一個自動包裝器,在其中傳遞io_service。 – genjix