我有以下模板函数:
template<typename T = CRecordset>
std::unique_ptr<T> ExecuteSqlQuery(LPCTSTR pszSqlQuery = nullptr, RecordsetMode nMode = RecordsetMode::read)
{
ASSERT(m_Database.IsOpen());
std::unique_ptr<ITableRecordset> prs = std::make_unique<T>(&m_Database);
if (!ExecuteSqlQuery(prs.get(), pszSqlQuery, nMode))
prs.reset();
return prs;
}
我这样调用它:
auto prs = db.ExecuteSqlQuery<CCustomerRecordset>(nullptr, RecordsetMode::bulkRead);
CCustomerRecordset
源自 CTableRecordset<>
, 和 CTableRecordset<>
源自 ITableRecordset
.
但是函数中的return语句报错:
Error C2440 'return': cannot convert from std::unique_ptr<ITableRecordset,std::default_delete<_Ty>>' to 'std::unique_ptr<CCustomerRecordset,std::default_delete<_Ty>>'
with
[
_Ty=ITableRecordset
]
and
[
_Ty=CCustomerRecordset
]
自 CCustomerRecordset
是 ITableRecordset
的一种,为什么我不能这样做?
最佳答案
您的示例简化为:
struct A {};
struct B : A {};
A *a = new B;
B *b = a;
return 语句试图返回 unique_ptr<ITableRecordset>
其中一个 unique_ptr<CCustomerRecordset>
是期待。这是一个沮丧,不会隐含地发生。修复它的一种方法是在整个函数模板中充分利用具体类型。所以不是转换为接口(interface):
auto prs = std::make_unique<T>(&m_Database);
关于c++ - 无法返回派生类型的 std::unique_ptr<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57743280/