【发布时间】:2015-05-22 03:29:30
【问题描述】:
我有一些类似的sql查询,所有选择的字段都是一样的,只是条件不同。因此,结果集处理程序也是相同的。我使用 sqlite3 和sqlite_modern_cpp。
这里有两个类似的功能(还有其他几个):
QVariantMap getItemById(int id) {
QVariantMap map;
database db(dbfile);
db << "select id,name,price,qty from items where id=?"
<< id
>> [&] (int id, std::string name, double price, int qty) {
map.insert("id", id);
map.insert("name", QString::fromStdString(name));
map.insert("price", price);
map.insert("qty", qty);
};
return map;
}
QVariantMap getItemByCatAndSeq(int cat, int seq) {
QVariantMap map;
database db(dbfile);
db << "select id,name,price,qty from items where cat=? and seq=?"
<< cat << seq
>> [&] (int id, std::string name, double price, int qty) {
map.insert("id", id);
map.insert("name", QString::fromStdString(name));
map.insert("price", price);
map.insert("qty", qty);
};
return map;
}
您看,查询中的所有字段都是“id,name,price,qty”,结果集处理程序也相同。
一个结果集处理程序就足够了,但我必须在每个函数中复制和粘贴相同的代码。另外,所选字段的名称和顺序必须与参数resultset handler--lambda函数相匹配。
如何消除这种重复代码?有没有更好的解决方案?提前致谢。
编辑:
我尝试了仿函数的方式,如下:
struct ItemResultHandler {
explicit ItemResultHandler(QVariantMap& map_) : map(map_) {}
void operator() ( int id, std::string name, double price, int qty ) {
map.insert("id", id);
map.insert("name", QString::fromStdString(name));
map.insert("price", price);
map.insert("qty", qty);
}
QVariantMap& map;
};
上面两个类似的函数之一会变成这样:
QVariantMap getItemById(int id) {
QVariantMap map;
database db(dbfile);
db << "select id,name,price,qty from items where id=?"
<< id
>> ItemResultHandler(map);
return map;
}
但是,它有编译错误:
../../myapp/src/utility/function_traits.h:12: error: type 'void (ItemResultHandler::*)(std::__1::basic_string<char>, std::__1::basic_string<char>, int, int)' cannot be used prior to '::' because it has no members
decltype(&Function::operator())
^
../../myapp/src/sqlite_modern_cpp.h:218: error: incomplete definition of type 'sqlite::utility::function_traits<ItemResultHandler>'
binder<traits::arity>::run(*this, func);
~~~~~~^~
【问题讨论】:
-
这似乎太明显了,但你不能把重复的代码放在一个函数中吗?
-
谢谢。变量映射是本地的,将重复的代码移动到函数中意味着我必须使用成员变量。这不是一个好办法。我尝试过仿函数,但它有编译错误。
-
通过引用传递变量映射?
标签: c++ database qt c++11 sqlite