【问题标题】:Is there a way to pass std::make_unique with different classes specified into a function有没有办法将 std::make_unique 与指定的不同类传递给函数
【发布时间】:2020-05-10 07:25:59
【问题描述】:

所以我得到了这个示例代码。这里总共使用了 4 个类似银行账户的类,其中 Account 是一个抽象基类。 CheckingAccount 和 SavingsAccount 派生自 Account 抽象类,而 TrustAccount 派生自 SavingsAccount。我不会在这里详细介绍类的内部工作原理,因为它对问题没有意义。我想用trycatch 以及从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;
    }
}

但我现在知道这怎么可能。 有没有办法创建指向类的指针? (类不是类的对象,我认为有一种方法可以创建指向函数的指针并将其作为参数传递,但我也不知道它是如何工作的)。

【问题讨论】:

    标签: c++ class exception smart-pointers


    【解决方案1】:

    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;
    }
    

    【讨论】:

    • 谢谢!这正是我所需要的。你救了我的命。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-20
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多