Program Language/C & C++
[C++] template를 이용하여 Bind 사용하기
야곰야곰+책벌레
2022. 5. 25. 16:29
728x90
반응형
bind를 사용하면 함수의 매개변수를 미리 지정하여 사용할 수 있다. 여기서 한 가지 주의할 점은 바인드로 보내는 참조자(&)는 값을 다시 가져오지 못하였다. 그래서 포인트로 강제하니 값을 얻어 올 수 있었다.
int test_func(int in, shared_ptr<int> out)
{
*out = in + 100;
return *out;
}
int main()
{
shared_ptr<int> out(new int);
// 바인드 사용하기
auto f(bind(test_func, 10, out));
f();
cout << "Bind Result : " << *out << endl;
}
여러 가지 함수에 대해서 bind를 사용하기 위해서 template로 만들어 본다.
template<typename Callable, typename... Args>
int templ_func(Callable func, Args... args)
{
auto f(bind(forward<Callable>(func), forward<Args>(args)...));
return f();
}
전달되는 함수에 매개변수를 자동으로 바인딩하고 실행시킨다.
// 템플릿 사용하기
using FUNC = int(*)(int, shared_ptr<int>);
templ_func<FUNC>(test_func, 100, out);
cout << "Template Result 1 : " << *out << endl;
함수 형태를 지정해주고 사용하면 된다. 이렇게 하면 여러 형태의 함수에 적용할 수 있다.
// 템플릿 사용하기
shared_ptr<int> out(new int);
using FUNC = int(*)(int, shared_ptr<int>);
templ_func<FUNC>(test_func, 100, out);
cout << "Template Result 1 : " << *out << endl;
using FUNC2 = double(*)(double, shared_ptr<double>);
shared_ptr<double> out2(new double);
templ_func<FUNC2>(test_func3, 100, out2);
cout << "Template Result 3 : " << *out2 << endl;
<전체 코드>
int test_func(int in, shared_ptr<int> out)
{
*out = in + 100;
return *out;
}
int test_func2(int in, shared_ptr<int> out)
{
*out = in + 600;
return *out;
}
double test_func3(double in, shared_ptr<double> out)
{
*out = in * 0.02332;
return *out;
}
template<typename Callable, typename... Args>
int templ_func(Callable func, Args... args)
{
auto f(bind(forward<Callable>(func), forward<Args>(args)...));
return f();
}
int main()
{
shared_ptr<int> out(new int);
// 바인드 사용하기
auto f(bind(test_func, 10, out));
f();
cout << "Bind Result : " << *out << endl;
// 템플릿 사용하기
using FUNC = int(*)(int, shared_ptr<int>);
templ_func<FUNC>(test_func, 100, out);
cout << "Template Result 1 : " << *out << endl;
templ_func<FUNC>(test_func2, 100, out);
cout << "Template Result 2 : " << *out << endl;
using FUNC2 = double(*)(double, shared_ptr<double>);
shared_ptr<double> out2(new double);
templ_func<FUNC2>(test_func3, 100, out2);
cout << "Template Result 3 : " << *out2 << endl;
return 0;
}
728x90
반응형