Function Over Guard

Background:
Sometimes, I want to call a specific function when the called function is over(return or throw an exception). The direct wat is to use the destructor.

void need_called_function()
{
std::cout<<"I am called"<<std::endl;
}
class FunctionOverGuard
{
public:
~FunctionOverGuard(){need_called_function();}
};
I want to write a generic version, as followings:

#include <iostream>
#include <functional>
template <class Ret, class...Args>
class FunctionOverGuard
{
std::function<Ret(Args...)> OverCalledFunction;
public:
FunctionOverGuard(std::function<Ret(Args...)> fun): OverCalledFunction(std::move(fun)){}
~FunctionOverGuard()
{
//There is a little confusedness, there is no inputed parameter.
//I ensured that the 'std::bind<>' template already has the inputed parameter( a substitute method of 'no inputed parameter')
OverCalledFunction();
}
};

void fun(){std::cout<<"I am called 1"<<std::endl;}
void gun(int i){std::cout<<"I am called "<<i<<std::endl;}
int main()
{
{
FunctionOverGuard<void()> f(std::bind(fun));
FunctionOverGuard<void(int)> f(std::bind(gun,1));
}
std::cin.get();
return 0;
}
Can you please use code tags when posting code, to make it readable?

http://www.cplusplus.com/articles/z13hAqkS/
If you want to provide parameter to the function called in the destructor your class need to store these parameter. I.e. you need to pass this parameter to the constructor.

As far as I know it is not possible to store arguments with unknown types.

Since you already bind all arguments to the function and the return type is irrelevant (what do you want to do with it?) you don't need templates for the function object at all.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <functional>
template <class Ret, class...Args>
class FunctionOverGuard
{
std::function<Ret(Args...)void()> OverCalledFunction;
public:
...

void fun(){std::cout<<"I am called 1"<<std::endl;}
void gun(int i){std::cout<<"I am called "<<i<<std::endl;}
int main()
{
{
FunctionOverGuard<void()> f(std::bind(fun));
FunctionOverGuard<void(int)> f(std::bind(gun,1));
}
std::cin.get();
return 0;
} 
I have wrote a generic version:
1
2
3
4
5
6
7
8
9
#include <functional>
template<class Result = void>
class FunctionOverGuard
{
	std::function<Result()> function_over_;
public:
	FunctionOverGuard(std::function<Result()> function_passing) : function_over_(function_passing){}
	~FunctionOverGuard() { function_over_(); }
};
Topic archived. No new replies allowed.