One of the problems that we have when using postgresql is the management of time stamps. This is especially true when using PQexecparams() for reasons that I will not go in to in this post; suffice it to say that when building INSERT statements that use time stamps you may need to get creative.
One of the problems that I have encountered is when overloading functions. This is because in essence time_t is of type int so if you have 2 overload functions thus, you will get a compile error.
void my_func(int i) {
//do_something.....
}
void myfunc(time_t i) {
//do_something.....
}
Using typedef is not an option because the compiler just sees it as an alias, resulting in the same error, so if we want to do this in a clean and easily readable manner then we need to get creative and use a struct which we are simply going to call tm_epoch.
#include <ctime>
struct tm_epoch {
const time_t te;
tm_epoch(time_t te)
:
te(te){}
};
All that we are doing here is creating a struct that we can pass a value that will be used to initialise a local time_t variable to use later.
Now when we declare our overloaded functions we will no longer have a compile error because one variable is of type int and the other is of type tm_epoch.
struct tm_epoch {
const time_t te;
tm_epoch(time_t te)
:
te(te){}
};
void my_func(tm_epoch t) {
//do_something...
}
void myfunc(int i) {
//do_something...
}
Now when we declare a variable of type tm_epoch and a variable of type int, when we call our overloaded function with the appropriate argument, the program will know which version of the function to call.
Here is a little proof of concept application that demonstrates how this works in practice:
#include <ctime>
#include <iostream>
using namespace std;
struct tm_epoch {
const time_t te;
tm_epoch(time_t te)
:
te(te){}
};
void myfunc(tm_epoch curTime) {
struct tm *ts {0};
ts = localtime(&curTime.te);
char buf[20];
strftime(buf, sizeof(buf), "%d-%m-%Y %H:%M:%S", ts);
cout << buf << endl;
}
void myfunc(int i) {
cout << i << endl;
}
int main() {
//Should be 2017-09-21 09:44:05
tm_epoch t = 1505983445;
int i = 1505983445;
myfunc(t);
myfunc(i);
return(0);
}

Recent Comments