c++ - 将不同的枚举类类型存储在单个变量中
问题描述
我有代表会计交易类型的枚举类,例如
enum class Liability
{
mortgage, creditors, overdraft, short_term_loans
};
enum class Income
{
sales, interest, rent, bad_debts_recovered, surplus, sundry
};
我有另一个用于费用,资产等。
我需要创建一个代表单个事务的类。考虑到会计原则,单个交易由两种交易类型组成,例如资产和负债,或资产和费用。
如何设计我的 Transaction 类,以便它只需要存储代表上述这些类型的两个变量,但可以用于我指定的任何枚举类?或者有没有更好的方法来设计这个场景?
编辑:我发现我可以将具有两个枚举作为不同类型的 Transaction 类模板化。我的问题是 - 我如何静态断言模板类型是我的枚举类类型之一?
解决方案
我最终使用了模板:
#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 等的枚举,然后创建了两个变量(借方和贷方),它们只是上述类型的联合。感谢任何建议工会的人!
推荐阅读
- python - 从命令行运行的multipledispatch ModuleNotFoundError
- javascript - 滑块中的按钮无法使用 javascript
- vim - 如何在vim中根据条件自动完成?
- http - Google Cloud App Engine 为第一个请求提供无法获取 /
- css - 使滑出到图标 img
- c++ - 在 Qt C++ 中形成父窗口后 n 秒后打开子窗口
- android - Android 应用程序包上传创建奇怪的帐户(
.<5 位数字>@gmail.com) 在 Firebase 身份验证中 - python - 加载 xgboost 模型返回 NoneType
- ios - 视频流未在 iphone 应用上显示视图
- android - 请求增量注释处理