Add Template variable parameter

Now, SQLDB::exec(SomeCommand,NormalFunction,NormalParamenters...) is
allowed.
Modern C++ !
This commit is contained in:
Kirigaya Kazuto 2017-04-19 09:16:28 +08:00
parent f264e7ce16
commit b9d10a9372
2 changed files with 35 additions and 0 deletions

View File

@ -36,6 +36,13 @@ bool SQLStatement::isReady() const
}
int _global_sqldb_executor(void* ExParam,int colNum,char** colVal,char** colName)
{
auto p=reinterpret_cast<std::function<int(int,char**,char**)>*>(ExParam);
return (*p)(colNum,colVal,colName);
}
void SQLDB::_set(sqlite3* p)
{
_db.reset(p,sqlite3_close);
@ -69,7 +76,17 @@ int SQLDB::step(const SQLStatement& Statement)
return sqlite3_step(Statement._getStmt());
}
int SQLDB::exec(const std::string& SQLCommand)
{
return _exec_real(SQLCommand,nullptr,nullptr);
}
int SQLDB::exec(const std::string& SQLCommand,SQLCallback callback,void* param)
{
return _exec_real(SQLCommand,callback,param);
}
int SQLDB::_exec_real(const std::string& SQLCommand,SQLCallback callback,void* param)
{
return sqlite3_exec(_get(),SQLCommand.c_str(),callback,param,&_errmsg);
}

View File

@ -27,6 +27,9 @@ private:
using SQLCallback = int (*)(void* ExParam,int colNum,char** colVal,char** colName);
/// Global Executor
int _global_sqldb_executor(void* ExParam,int colNum,char** colVal,char** colName);
class SQLDB
{
public:
@ -37,10 +40,25 @@ public:
int open(const std::string& filename);
SQLStatement prepare(const std::string& SQLCommand);
int step(const SQLStatement& Statement);
template<typename Callable,typename... Args>
int exec(const std::string& SQLCommand,Callable&& callable,Args&&... args)
{
auto realCall=[&](int colNum,char** colVal,char** colName)->int{return callable(colNum,colVal,colName,args...);};
std::function<int(int,char**,char**)> func=realCall;
return _exec_real(SQLCommand,_global_sqldb_executor,&func);
}
int exec(const std::string& SQLCommand);
/// Reserved For Capability
int exec(const std::string& SQLCommand,SQLCallback callback,void* param);
const char* getErrorMsg();
void clearError();
private:
int _exec_real(const std::string& SQLCommand,SQLCallback callback,void* param);
sqlite3* _get();
void _set(sqlite3*);
std::shared_ptr<sqlite3> _db;