Language/C++ 11

[C++11] std::function() 을 이용한 클래스 멤버 함수 저장 및 사용

마탁이 2021. 2. 28. 16:05

C++ 11에서 std::function()을 이용해 함수를 미리 객체화하여 저장할 수 있다고 하여 아래와 비슷하게 코드를 사용하고 있다.

Modern C++이나 C++ 11을 자세하게 이해한 후 코드를 실제 사용하는 코드에 대해 개선이 필요하다.

 

 - ReigsterFunc()을 이용해 함수를 객체화하여 저장, Exec를 통해 key에 따라 함수를 실행.

#include <functional>
#include <unordered_map>

template <class T>
class State
{
public:
	void RegisterFunc(uint16_t keyEvent, std::function<void(T&, std::string&)> linkedFunc)
	{
		std::pair<uint16_t, std::function<void(T&, std::string&)>> pair(keyEvent, linkedFunc);
		m_states.insert(pair);
	}

	void Exec(uint16_t keyEvent, std::string &str)
	{
		if (m_states.end() != m_states.find(keyEvent))
		{
			T linkedClass;
			std::function<void(T&, std::string &)> execFunc= m_states[keyEvent];
			execFunc(linkedClass, str);
		}
	}

private :
	std::unordered_map<uint16_t, std::function<void(T&, std::string&)>> m_states;
};

 

 - main.cpp

#include <iostream>
#include "State.h"

class TestClass
{
public:
	void Print(std::string &str)
	{
		printf("%s \n", str.c_str());
	}
};

int main()
{
	State<TestClass> state;
	state.RegisterFunc(3, &TestClass::Print);

	std::string hello = "hello";
	state.Exec(3, hello);
}