这是在 os x yosemite 上,来自 clion 中 xcode 7.2 的 clang。
我正在遍历来自 postgresql 数据库的查询并将结果添加到 json 对象。
for (pqxx::result::const_iterator c = R.begin(); c != R.end(); ++c) {
participants["participants"] += { \
{"id", c[0].as<std::string>()},
{"location", c[1].as<std::string>()},
{"racename", c[2].as<std::string>()},
{"racestart_at", c[3].as<std::string>()},
{"ended_at", static_cast<bool>(c[9].size()) ? c[9].as<std::string>() : ""},
{"racetime", static_cast<bool>(c[10].size()) ? c[10].as<std::string>() : ""}
};
}
一些列具有空值,因此我在三元运算符中测试转换为 bool 并返回结果或空字符串。为了让它更清晰一点,我尝试使用 http://www.cprogramming.com/tutorial/templated_functions.html 中的示例添加模板函数。并且有这个:
template <class T>
std::string column_content(T a) {
return static_cast<bool>(a.size()) ? a.as<std::string>() : "";
}
当我尝试编译程序时出现错误:
Database.cpp:9:44: error: use 'template' keyword to treat 'as' as a dependent template name
return static_cast<bool>(a.size()) ? a.as<std::string>() : "";
^
template
我看了Cast Chars To Int in Template Function和 http://www.cplusplus.com/doc/oldtutorial/templates/和谷歌的其他建议,但看起来我使用了错误的语法,但我无法发现它。
如果我可以使用添加到 json 的模板函数,那么看起来会像
{"start_at", column_content(c[8])}
问候 克劳斯
最佳答案
我暂时改成了函数。根据 http://pqxx.org/devprojects/libpqxx/doc/2.6.9/html/Reference/a00259.html#2a9d36599b217ebfde2cac4633856ac0 传递的类型是 pqxx::result::field .
std::string column_content(pqxx::result::field a) {
if (static_cast<bool>(a.size())) {
return a.as<std::string>();
} else {
return "";
}
}
关于c++ - 具有 pqxx 结果的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34455530/