我有一个带有枚举值作为参数的类。它有一个成员m_ConsistencyErrors
,它是std::set
。我想根据枚举参数的值在构造时设置此成员的类型。
如果TestType值为
MSG123_CONSISTENCY_TEST
,我希望m_ConsistencyErrors的类型为std::set<EnMsg123Param>
如果TestType值为
MSG5_CONSISTENCY_TEST
,我希望m_ConsistencyErrors的类型为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;
};
答案 0 :(得分:1)
您不能这样做,当您使用 CMsgConsistencyTest 及其成员访问m_ConsistencyErrors
为此, 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;
否则,您可能需要做一些丑陋的,灾难性的事情以及类似“ non 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;