std :: bind 함수 랩퍼가 필요합니다. 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;
}
오류를 말한다 : 아직까지 전화 'foo는 (무효 (&) (INT))'
에 대한 매칭 기능, 코드 샘플 :
template<typename T>
void foo(T t)
{
}
int main()
{
foo(99);
return 0;
}
이 작동하지 않습니다. 어떤 아이디어가이 작품을 만드는 방법? std :: bind를 전달할 수 있어야하고 결과가 std :: function으로 성공적으로 캐스팅 될 수 있어야합니다.
어떻게 템플릿 매개 변수를 제거 할 수 있습니까? 감사.
Q. 서비스 란 무엇이며이 클래스는 무엇을 의미합니까?
가. 현재 스레드에서 boost :: asio :: io_service-> posts의 함수 래퍼를 캡슐화합니다.
전체 소스 코드 :
template <typename R, typename A>
struct wrap
{
typedef std::function<R(A)> func;
wrap(func f_) : f(f_) { }
void prebind(func g) { prebound.push_back(g); }
R operator()(A arg)
{
for (auto it = prebound.cbegin(); it != prebound.cend(); ++it)
{
func g = *it;
g(arg);
}
f(arg);
}
private:
std::vector<func> prebound;
func f;
};
wrap<void, int> make_wrap(std::function<void(int)> f)
{
return wrap<void, int>(f);
}
:
#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의 일부인 경우 내부적으로 thread_ugly를 전환하기 위해 handle_connect를 do_handle_connect에 게시해야합니다. 차라리 io_service를 전달하는 자동 래퍼가 필요합니다. – genjix