C++模板类编译错误排查:std::shared_ptr创建失败问题咨询
问题分析与修复方案
先拆解你代码里的编译错误,再聊聊可以优化的设计细节:
1. 直接触发编译失败的语法问题
在main.cpp的最后一行,有两处明显的语法错误:
- 模板参数括号不匹配:声明
std::shared_ptr时,模板参数的闭合>数量不足。你写的是std::shared_ptr<Repository< bool, std::shared_ptr<Client>, std::vector<std::shared_ptr<Client>> > p,最后少了一个闭合的>,正确写法应该是std::shared_ptr<Repository<bool, std::shared_ptr<Client>, std::vector<std::shared_ptr<Client>>>> p(注意末尾的两个>)。 make_shared调用错误:std::make_shared<ClientRepository>;;多写了一个分号,且缺少构造函数调用的括号,正确写法是std::make_shared<ClientRepository>()。
修复后的main函数对应行:
std::shared_ptr<Repository<bool, std::shared_ptr<Client>, std::vector<std::shared_ptr<Client>>>> p = std::make_shared<ClientRepository>();
2. 模板设计的冗余优化
你的Repository模板定义了三个参数,但第三个参数VectorOfSmarPtrs本质就是std::vector<typeShared_ptr>,完全可以通过第二个参数推导出来,没必要单独作为模板参数,这样能减少重复代码和出错概率。
修改后的Repository.hpp:
#ifndef REPOSITORY_HPP #define REPOSITORY_HPP #include <vector> #include <string> template<typename BoolType, typename EntityPtr> class Repository { protected: std::vector<EntityPtr> nameOfVector; public: virtual BoolType create(const EntityPtr&) = 0; }; #endif
对应的ClientRepository.hpp继承代码也可以简化:
#ifndef CLIENTREPOSITORY_HPP #define CLIENTREPOSITORY_HPP #include <memory> #include <string> #include "Client.hpp" #include "Repository.hpp" class ClientRepository : public Repository<bool, std::shared_ptr<Client>>{ public: bool create(const std::shared_ptr<Client> & newClient) override; }; #endif
此时main里的声明会更简洁:
std::shared_ptr<Repository<bool, std::shared_ptr<Client>>> p = std::make_shared<ClientRepository>();
3. 代码风格与安全性优化
- 在
ClientRepository.cpp中,判断智能指针是否为空应该用C++11推荐的nullptr而非NULL; - 遍历vector时,范围for循环比索引遍历更安全、易读;
- 返回布尔值时,用
true/false代替1/0,语义更清晰。
修改后的ClientRepository.cpp:
#include "ClientRepository.hpp" bool ClientRepository::create(const std::shared_ptr<Client> & newClient) { if(newClient != nullptr){ for(const auto& client : this->nameOfVector) { if(client->GetPersonalID() == newClient->GetPersonalID()) { return false; } } this->nameOfVector.push_back(newClient); return true; } else { return false; } }
最终修复后的main.cpp片段
#include <iostream> #include <memory> #include "Client.hpp" #include "ClientRepository.hpp" #include "Repository.hpp" int main(){ ClientRepository x; std::shared_ptr<Repository<bool, std::shared_ptr<Client>>> p = std::make_shared<ClientRepository>(); }
内容的提问来源于stack exchange,提问作者KKMKK
相关产品推荐
相关产品推荐

