![](/img/trans.png)
[英]pqxx::result::tuple has not been declared (PostgreSQL library for c++)
[英]PostgreSQL C++ (pqxx) and setting value if not NULL
我有一些看起来像这样的代码:
for (const auto& query_result_row : query_result) {
my_struct.a = query_results_row["a"].as<int>();
my_struct.b = query_results_row["b"].as<string>();
// and so forth.
}
一般来说,可能有很多不同类型的字段。 这很好,但是如果选定的字段是 NULL,这将引发异常。 所以我现在写了这个,这很尴尬,而且很容易出错:
for (const auto& query_result_row : query_result) {
if (!query_results_row["a"].is_null()) {
my_struct.a = query_results_row["a"].as<int>();
}
if (!query_results_row["ab"].is_null()) {
my_struct.b = query_results_row["b"].as<string>();
}
// and so forth.
}
伊克。
也许,我想,我可以制作一个(模板化的)function 来简化这一点:
for (const auto& query_result_row : query_result) {
MaybeSet(my_struct.a, query_results_row["a"]);
MaybeSet(my_struct.b, query_results_row["b"]);
// and so forth.
}
这里的问题是query_results_row["a"]
本身就是一个模板类型,而且, as()
类型可能与my_struct
类型不完全相同(例如,不同类型的整数),虽然我不今天看到它,这闻起来像是某天可能导致意外演员表的那种东西。
// Doesn't work.
template <typename valueT, typename postgresFieldT>
void MaybeSet(valueT& my_struct_field, const postgresFieldT& field) {
if (!field.is_null()) {
my_struct_field = field.as<valueT>();
}
}
如果它们不是 null 但不尝试的话,有什么建议可以更简洁地表达设置事物的想法吗?
对于后代:我稍微改变了问题,因此得出了一个简单的解决方案。
template <typename T>
class SetThing {
// ...
void MaybeSet(const pqxx::result::field& field) {
if (!field.is_null()) {
SetClean(field.as<T>());
}
}
template <typename asT>
void MaybeSet(const pqxx::result::field& field) {
if (!field.is_null()) {
SetClean(field.as<asT>());
}
}
// ...
}
用法然后变成
SetThing thing;
thing.MaybeSet(query_result_row["dog"]);
thing.MaybeSet<the_cast_type>(query_result_row["complicated"]);
第二种形式用于少数复杂类型(例如,类),我可以从简单的东西(例如,int 或字符串)构造它们,但它不是SetThing
的基本(模板化)类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.