gpt4 book ai didi

c++ - 根据参数在构造函数中设置成员数据类型

转载 作者:行者123 更新时间:2023-11-28 04:24:29 26 4
gpt4 key购买 nike

我有一个以枚举值作为参数的类。它有一个成员 m_ConsistencyErrors 这是 std::set .我想根据枚举参数的值在构造时设置此成员的类型。

if TestType value is MSG123_CONSISTENCY_TEST I would like m_ConsistencyErrors to be of type std::set<EnMsg123Param>

if TestType value is MSG5_CONSISTENCY_TEST I would like m_ConsistencyErrors to be of type std::set<EnMsg5Param>

是否有一种干净的方法来实现这一点,或者我应该找到另一种解决方案。

class CMsgConsistencyTest // : public CTestBase  // left out for simplicity
{
enum EnTests
{
MSG123_CONSISTENCY_TEST,
MSG5_CONSISTENCY_TEST,
};
enum EnMsg123Param
{
Msg123_1,
Msg123_2
};
enum EnMsg5Param
{
Msg5_1,
Msg5_2
};

public:
CMsgConsistencyTest(const EnTests TestType) // : CTestBase(TestType) // left out for simplicity
{
if (TestType == MSG123_CONSISTENCY_TEST)
{
ParameterType = EnMsg123Param; // pseudo code
}
else if (TestType == MSG5_CONSISTENCY_TEST)
{
ParameterType = EnMsg5Param; // pseudo code
}
}

private:
template<typename ParameterType>
std::set<ParameterType> m_ConsistencyErrors;
};

最佳答案

你不能那样做,当你使用 CMsgConsistencyTest 并且当它的成员访问 m_ConsistencyErrors

时, ParameterType 必须一直知道>

CMsgConsistencyTest 可以是模板类,例如

#include <set>

enum EnMsg123Param
{
Msg123_1,
Msg123_2,
};

enum EnMsg5Param
{
Msg5_1,
Msg5_2,
Msg5_3,
};

template<typename ParameterType>
class CMsgConsistencyTest // : public CTestBase // left out for simplicity
{
public:
// ...
private:
std::set<ParameterType> m_ConsistencyErrors;
};

// and for instance

CMsgConsistencyTest<EnMsg123Param> A;
CMsgConsistencyTest<EnMsg5Param> B;

否则你可能不得不做一些丑陋的、灾难性的和“非 C++”的事情:

   CMsgConsistencyTest(const EnTests TestType) //  : CTestBase(TestType)  // left out for simplicity
{
if (TestType == MSG123_CONSISTENCY_TEST)
{
m_ConsistencyErrors = new set<EnMsg123Param>;
}
else if (TestType == MSG5_CONSISTENCY_TEST)
{
m_ConsistencyErrors = new set<EnMsg5Param>;
}
// else ?
// probably need to save TestType etc
}

private:
void * m_ConsistencyErrors;

关于c++ - 根据参数在构造函数中设置成员数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54695374/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com