profile image

L o a d i n g . . .

반응형

UI 구현 시 이곳저곳에 버튼이 참 많이 들어간다. 이 경우 차라리 하나의 클래스로 뽑아서, 버튼이 클릭되면 지정한 함수를 호출하는 기능을 하게끔 구현하려고 하였다.

 

함수 포인터를 이용하니 static 선언이 없으면 불가능했으며, static으로 선언된 멤버 함수에서는 멤버 변수 및 다른 멤버 함수에 접근하는 게 불가능하기 때문에 원하는 동작을 원활하게 실행할 수가 없었다.

 

std::function, std::bind

나의 경우 <functional>의 std::function, std::bind를 이용하였다.

class button
{
// ...
    function<void(void)> _callbackFunction;
}

 

생성자나 함수를 이용하여 _callbackFunction을 초기화하면 된다. 이때 인스턴스의 바인딩이 필요함에 주의한다.

	_btnSceneChange->init("버튼", WINSIZEX / 2, WINSIZEY / 2,
		PointMake(0, 1), PointMake(0, 0), std::bind(&anotherScene::cbSceneChange, this));

 

 

참고 사이트

https://en.cppreference.com/w/cpp/utility/functional/function

 

std::function - cppreference.com

template< class > class function; /* undefined */ (since C++11) template< class R, class... Args > class function ; (since C++11) Class template std::function is a general-purpose polymorphic function wrapper. Instances of std::function can store, copy, an

en.cppreference.com

https://www.oreilly.com/library/view/c-high-performance/9781787120952/09071a8e-60f1-43d7-bd9e-1f2a58ca1fe5.xhtml

 

C++ High Performance

Implementing a simple Button class with std::function Let's put the std::function to use in something that resembles a real-world example. If we create a Button class, we can use the … - Selection from C++ High Performance [Book]

www.oreilly.com

 

반응형
복사했습니다!