2014-12-22 2 views
4

이 foo 함수를 생성자 대신 action 멤버 함수에서 호출하려고합니다.
그 때문에 어딘가에서 값을 저장해야합니다.
구문을 이해할 수 없습니다.가변 인수 형식의 인수를 저장하려면 어떻게해야합니까?

#include <iostream> 
void foo(int a, int b) 
{ 
    std::cout<<a<<b; 
} 
template<typename... Args> 
struct Foo 
{ 
public: 
    Foo(Args... args){foo(args...);} 
    void action(){} 
private: 
    //Args... ? 
}; 

int main() 
{ 
    Foo<int,int> x(1,2); 
} 
+2

['std :: function'] (http://en.cppreference.com/w/cpp/utility/functional/function) –

+1

... 및/또는 ['std :: bind'] (http://en.cppreference.com/w/cpp/utility/functional/bind). – filmor

+1

... [std :: forward] (http://en.cppreference.com/w/cpp/utility/forward) –

답변

4

당신은 std::functionstd::bindFoo의 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를 사용할 수있는 경우) 대신에 바인딩을 고려하십시오.

+0

'Foo '의 작성자는 때때로'std :: ref'를 사용해야 할 수도 있음에 유의하십시오. – Yakk

+0

함수가 실제로 다른 객체의 생성자이면 어떻게 될까요? 새로운 Type (args)을 호출해야합니다. – manasij7479

+0

@ manasij7479 생성자는 이름이없는 멤버 함수이므로 함수 호출과 같이 직접 호출 할 수 없습니다. 'new T (args ...)'를 호출하기 위해 호출되는 도우미 함수를 생성해야합니다. –

관련 문제