我有这个问题。它不断抛出错误:
use of class template 'std::unique_ptr' requires template arguments
Run Code Online (Sandbox Code Playgroud)
我已经搜索了一个小时。我试过用c++17编译,还是不行。如何让 MariaDB 连接器正常工作?我安装了 MariaDB 连接器。我在 Debian 10 上。并使用 clang++ v7 进行编译。我尝试在标题中添加 <template> 选项,但仍然无效。
我正在使用这个编译: clang++ -I/usr/include/mariadb/concpp/compat -O3 -Wall -o ./getUsers ./getUsers.cpp -lmariadbcpp
#include <iostream>
#include <cstring>
#include <mariadb/conncpp.hpp>
using namespace std;
// Main Process
int main(){
try {
// Instantiate Driver
sql::Driver* driver = sql::mariadb::get_driver_instance();
// Configure Connection
sql::SQLString url("jdbc:mariadb://x.x.x.x:3306/todo");
sql::Properties properties({{"user", "xxxx"}, {"password", "xxxx"}});
// Establish Connection
std::unique_ptr conn(driver->connect(url, properties));
// Create a new Statement
std::unique_ptr stmnt(conn->createStatement());
// Execute query
sql::ResultSet *res = stmnt->executeQuery("SELECT id, username FROM accounts");
// Loop through and print results
while (res->next()) {
std::cout << res->getInt("id") << ") ";
std::cout << res->getString("username");
}
}
catch(sql::SQLException& e){
std::cerr << "Error selecting tasks: " << e.what() << std::endl;
}
delete res;
delete stmnt;
delete conn;
// Exit (Success)
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器是对的:使用类模板std::unique_ptr需要模板参数。您必须为该std::unique_ptr类型提供模板参数。
// ...
// v---------------v---- template arguments
std::unique_ptr<sql::Connection> stmnt(conn->createStatement());
// ...
// v----------------------v----- same here
std::unique_ptr<sql::PreparedStatement> stmnt(conn->createStatement());
Run Code Online (Sandbox Code Playgroud)
C++17 可以正常推断类模板的类型,但std::unique_ptr不能。该std::unique_ptr构造函数不能演绎类型,由于它的定义方式,并扣除导游还没有被添加到std::unique_ptr故意。这是因为原始数组和指针都以相同的方式传递,因此std::unique_ptr无法区分int*和int[],它们的删除方式不同。这是 C 的一个怪癖,它仍然影响 C++ 中的设计选择。
现在,您还删除了唯一指针,但这不是隐性的。
// Res is not a unique pointer, you still need to delete it.
delete res;
// You don't need that, those are unique pointers, remove it from your code.
delete stmnt;
delete conn;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
48 次 |
| 最近记录: |