C++でcallback
Higher-Order Perlにでてきたハノイの塔をC++で書いてみた。
#include <iostream>
#include <string>
#include <functional>
#include <boost/bind.hpp>
#include <boost/function.hpp>
using namespace boost;
class peg {
public:
explicit peg(const std::string& name) : name(name){ }
const std::string name;
};
void print_move(int disk, const peg& start, const peg& end);
void hanoi(int n, const peg& start, const peg& end, const peg& extra, function<void (int, const peg&, const peg&)> f);
int main(void)
{
//call back function
function<void (int, const peg&, const peg&)> f;
f = &print_move;
hanoi(3, peg("A"), peg("C"), peg("B"), f);
return 0;
}
void print_move(int disk, const peg& start, const peg& end){
std::cout << "Move disk #" << disk << " from " << start.name << " to " << end.name << std::endl;
}
void hanoi(int n, const peg& start, const peg& end, const peg& extra, function<void (int, const peg&, const peg&)> f)
{
if(n==1) {
f(n , start, end);
} else {
hanoi(n-1, start, extra, end, f);
f(n, start, end);
hanoi(n-1, extra, end, start, f);
}
}
動かしてみる。
YUKI.N>./kati.pl
g++ -c -I/usr/include/boost-1_33_1 -g -W -Wall -ansi -pedantic hanoi.cpp
g++ -o hanoi hanoi.o -I/usr/include/boost-1_33_1 -g -W -Wall -ansi -pedantic
YUKI.N>./hanoi.exe
Move disk #1 from A to C
Move disk #2 from A to B
Move disk #1 from C to B
Move disk #3 from A to C
Move disk #1 from B to A
Move disk #2 from B to C
Move disk #1 from A to C
C++でcallbackは出来るようになった。
The comments to this entry are closed.


Comments