2016-10-13 2 views
0

저는 std::function 개념을 처음 사용합니다.std :: function을 템플릿으로 사용하는 방법

나는 다른 개체에서 다른 매개 변수를해야 여기 std::function<void()>

class A(string ,bool, string, std::function<void()>) 

을 다음과 같이 나는 클래스가 방법

다음의 std::function를 사용해야합니다. 매개 변수는 나는 내가 클래스 A의 객체를 매개 변수로 다른 열거를 통과 할 수 있도록 전 클래스 A의 std::function을 구성하는 방법을 알고 싶어

1)A a(string ,bool, string, std::function<void(enum xyz)>) 
2)A b(string ,bool, string, std::function<void(enum abc)>) 
3)A c(string ,bool, string, std::function<void(enum efg)>) 

예를 들어 열거

의 기본적으로 다른 종류의 것

+0

어떻게'std :: function'을 사용하고 싶습니까? – Jarod42

+0

매개 변수가있는 클래스? 당신은 건설업자를 말하는 거죠? – DogeAmazed

+0

템플릿으로 사용 하시겠습니까? 무엇 – amanuel2

답변

1

템플릿 유형을 std::function 매개 변수로 전달할 수 있습니다. 다음 예는 다음과 같습니다

#include <iostream> 
#include <functional> 
#include <string> 

template <class T> 
class Foo 
{ 
public: 
    Foo(std::function<void(T)> f) : f_{f} {} 

    void call(T in) { f_(in); } 

private: 
    std::function<void(T)> f_; 
}; 

int main() 
{ 
    Foo<double> fd{[] (double d) { std::cout << d << '\n'; }}; 
    fd.call(34.2); 

    Foo<std::string> fs{[] (std::string s) { std::cout << s << '\n'; }}; 
    fs.call("Test!"); 
    return 0; 
} 

출력 :

34.2 
Test! 
+0

고마워요. 이 방법을 사용하면 누군가가 문제를 해결할 수있는 경우 – user5222584

+0

@ user5222584에 도움이됩니다. 체크 표시를 클릭하여 문제를 해결 한 것으로 표시하십시오. 덕분에 – Yakk

0

질문을보고 한 후, 이것이 당신이 기능을 사용해야하는 방법이다.

#include <iostream> 
#include <string> 
#include <functional> //Need to include for std::function use 

using namespace std; 

//Declare the ENUM here. 
enum ePat {xyz=1,abc,efg,mno}; 
enum ePat_second {def=1,ghi,jkl,opq}; 


//utility function you want to pass to std function 
template <typename T> 
void print(T e) 
{ 

} 

template <typename T> 
class A 
{ 
    public: 

    //Constructore with std function as one of the argument 
    A(string ,bool , string, std::function<void(T)>) 
    { 


    } 

}; 

int main() 
{ 
    //Declare your std function types. 
    std::function<void(ePat)> xyz_display = print<ePat>; 
    std::function<void(ePat_second)> def_display = print<ePat_second>; 


    //Pass it to the object. 
    A<ePat> a("abc" ,true, "abc",xyz_display); 
    A<ePat_second> b("def" ,true, "def",def_display); 
} 
+0

. 하지만 다른 열거 형이 있습니다 – user5222584

+0

그래서 모든 개체에 걸쳐 사용되는 명확한 열거 형을 가지고 있지 않습니다. – user5222584

+0

ok. 더 나은 프로토 타입을 시도 할 것입니다 – Naidu

관련 문제