당신은 std::function
및 std::bind
와 Foo
의 templatisation을 포기 할 수
#include <functional>
#include <iostream>
void foo(int a, int b)
{
std::cout<<a<<b;
}
struct Foo
{
public:
template<typename... Args>
Foo(Args&&... args)
// bind the arguments to foo
: func_(std::bind(foo, std::forward<Args>(args)...)) { }
// then you're able to call it later without knowing what was bound to what.
void action(){ func_(); }
private:
std::function<void()> func_;
};
int main()
{
Foo x(1,2);
x.action();
}
편집 : 나는
template<typename T, typename... Args> T *make_new(Args&&... args) {
return new T(std::forward<Args>(args)...);
}
같은 함수 템플릿을 사용하십시오 생성자를 바인딩, 코멘트에 대답하기 위해
그리고 나서
std::bind(make_new<SomeClass, Args...>, std::forward<Args>(args)...)
중요 스타일 참고 : 스마트 포인터의 이점을 무료로 얻으려면 또는 std::make_unique
(C++ 14를 사용할 수있는 경우) 대신에 바인딩을 고려하십시오.
['std :: function'] (http://en.cppreference.com/w/cpp/utility/functional/function) –
... 및/또는 ['std :: bind'] (http://en.cppreference.com/w/cpp/utility/functional/bind). – filmor
... [std :: forward] (http://en.cppreference.com/w/cpp/utility/forward) –