所以我有这个示例代码。这里总共使用了4个类似银行帐户的类,其中Account是一个抽象基类。 CheckingAccount和SavingsAccount源自Account抽象类,而TrustAccount源自SavingsAccount。我不会在这里详细介绍类的内部工作原理,因为它对问题没有任何意义。我想用try
和catch
以及从std::exception
派生的包含异常警告的类来实现简单的异常处理。我可以编写一个对n个对象执行此操作的函数,但前提是它们必须是Account的相同子类。但是,我想向向量添加3个不同的子类,但我想不出一种自动的方法。
#include <iostream>
#include <memory>
#include <vector>
#include "checking_account.h"
#include "trust_account.h"
#include "account_util.h"
int main() {
std::vector<std::unique_ptr<Account>> accounts{}; //A vector of unique_ptr to Account objects that I will be adding new Objects to
std::unique_ptr<Account>
try {
accounts.push_back(std::make_unique<CheckingAccount>("Joe", 200));
}
catch (const std::exception &ex) {
std::cout << ex.what() << std::endl;
}
try {
accounts.push_back(std::make_unique<TrustAccount>("John", -300, 0.1));
}
catch (const std::exception &ex) {
std::cout << ex.what() << std::endl;
}
try {
accounts.push_back(std::make_unique<SavingsAccount>("Jane", 150, 0.2));
}
catch (const std::exception &ex) {
std::cout << ex.what() << std::endl;
}
return 0;
}
我想制作一个看起来像这样的函数
void create_account(std::vector<std::unique_ptr<Account>> &accounts, CLASS, CLASS_ARGS) {
try {
accounts.push_back(std::make_unique<CLASS>(CLASS_ARGS));
}
catch (const std::exception &ex) {
std::cout << ex.what() << std::endl;
}
}
但是我现在已经知道那怎么看。 有没有办法创建指向类的指针? (类不是类的对象,我认为有一种方法可以指向函数并将其作为参数传递,但我也不知道该如何工作)。
答案 0 :(得分:3)
使create_account()
为模板函数,例如:
template<typename T, typename... ArgTypes>
void create_account(std::vector<std::unique_ptr<Account>> &accounts, ArgTypes&&... args)
{
try {
accounts.push_back(std::make_unique<T>(std::forward<ArgTypes>(args)...));
}
catch (const std::exception &ex) {
std::cout << ex.what() << std::endl;
}
}
int main() {
std::vector<std::unique_ptr<Account>> accounts;
create_account<CheckingAccount>(accounts, "Joe", 200);
create_account<TrustAccount>(accounts, "John", -300, 0.1);
create_account<SavingsAccount>(accounts, "Jane", 150, 0.2);
return 0;
}