2020년 7월 1일 수요일

Function Pointer 예제

//Function Pointer
// 리턴type(*name)(매개변수)


class Game
{
public:
static void Start(int number)
{
printf("%d번 게임 시작!!\n", number);
}
void Render(int number)
{
printf("%d번 렌더링\n", number);
}
};

class Luncher
{
public:
Luncher()
{
start_func = Game::Start;
render_func = &Game::Render; // 여기선 레퍼런스랑은 다름, 위치만 정하는거
}
void Execute(int number)
{
start_func(10);
Game game;
(game.*render_func)(10);
}
private:
void(*start_func)(int) = nullptr;
void(Game::*render_func)(int) = nullptr;
};

class Test
{
public:
static void Tmp()
{
printf("Test Tmp\n");
}

void Tmp2(int a, int b)
{
printf("Test Tmp2 %d %d\n", a, b);
}

std::string Tmp3(std::string str, int a, int b)
{
return str + "Tmp3" + std::to_string(10*a + b);
}

};

void MoveRight();
void MoveLeft();
std::string Printf(int direction);


int main()
{
void(*MoveR)() = MoveRight;
void(*MoveL)() = MoveLeft;
MoveR();
MoveL();

void(*Move[2])() = { MoveRight, MoveLeft };

Move[0]();
Move[1]();

std::vector<void(*)()> Moves;
Moves.push_back(MoveLeft);
Moves.push_back(MoveRight);
Moves[0]();
Moves[1]();

std::string(*Func)(int) = Printf;

while (true)
{
int direction = -1;
if (GetAsyncKeyState(VK_LEFT) & 0x8000 == 0x8000)
direction = 0;
if (GetAsyncKeyState(VK_RIGHT) & 0x8000 == 0x8000)
direction = 1;
if (direction > -1)
{
std::string str = Func(direction);
printf("%s\n", str.c_str());
break;
}
}

Luncher* luncher = new Luncher();
luncher->Execute(100);
delete luncher;



std::function<void()> func0 = nullptr; // -> void(*func1)() = nullptr;
func0 = MoveRight;
if (func0 != nullptr)
func0();

std::function<void()> funcs[2];
funcs[0] = MoveRight;
funcs[1] = std::bind(MoveLeft);

funcs[0]();
funcs[1]();

std::vector<std::function<void()>> funcss;
funcss.push_back(MoveRight);
funcss.push_back(std::bind(MoveLeft));
funcss.push_back(std::bind(Test::Tmp));

for (auto func_ : funcss)
func_();

Test test;
std::function<void()> func1;
func1 = std::bind(&Test::Tmp);

std::function<void(int, int)> func2;
func2 = std::bind(&Test::Tmp2, test, std::placeholders::_1, std::placeholders::_2);
func2(100, 200);

std::function<std::string(std::string, int, int)> func3;
func3 = std::bind(&Test::Tmp3, test, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);

std::string str = func3("Test", 300, 700);
printf("%s\n", str.c_str());
return 0;
}

void MoveRight()
{
printf("우로 이동\n");
}

void MoveLeft()
{
printf("좌로 이동\n");
}

std::string Printf(int direction)
{
std::string str = "이동방향 : " + std::to_string(direction);
return str;
}

댓글 없음:

댓글 쓰기

List