首页 > 解决方案 > 将不同的枚举类类型存储在单个变量中

问题描述

我有代表会计交易类型的枚举类,例如

enum class Liability
{
    mortgage, creditors, overdraft, short_term_loans
};

enum class Income
{
    sales, interest, rent, bad_debts_recovered, surplus, sundry
};

我有另一个用于费用,资产等。

我需要创建一个代表单个事务的类。考虑到会计原则,单个交易由两种交易类型组成,例如资产和负债,或资产和费用。

如何设计我的 Transaction 类,以便它只需要存储代表上述这些类型的两个变量,但可以用于我指定的任何枚举类?或者有没有更好的方法来设计这个场景?

编辑:我发现我可以将具有两个枚举作为不同类型的 Transaction 类模板化。我的问题是 - 我如何静态断言模板类型是我的枚举类类型之一?

标签: c++

解决方案


我最终使用了模板:

#include <type_traits>

template<typename Debit, typename Credit>
class Transaction
{
public:
    Transaction(int amount, Debit debitType, Credit creditType)
    {
        constexpr bool validDebitType = (std::is_same<Debit, Expense>::value) || (std::is_same<Debit, Asset>::value) || (std::is_same<Debit, Liability>::value) || (std::is_same<Debit, Income>::value);
        constexpr bool validCreditType = (std::is_same<Credit, Expense>::value) || (std::is_same<Credit, Asset>::value) || (std::is_same<Credit, Liability>::value) || (std::is_same<Credit, Income>::value);
        static_assert(validDebitType && validCreditType);
        m_amount = amount;
        m_debitType = debitType;
        m_creditType = creditType;
    }

private:
    int m_amount;
    Debit m_debitType;
    Credit m_creditType;
};

仍然欢迎更好的解决方案

编辑:原来存储实际类型本身的枚举是我的解决方案。我创建了另一个带有值 Expense、Income、Asset 等的枚举,然后创建了两个变量(借方和贷方),它们只是上述类型的联合。感谢任何建议工会的人!


推荐阅读