简体   繁体   中英

Set a Members Data Type in Constructor Depending on Parameter

I have a class with an enum value as a parameter. It has a member m_ConsistencyErrors which is a std::set . I would like to set the type of this member at construction depending on the value of the enum parameter.

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>

Is there a clean way to achieve this or should i find another solution.

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

You cannot do that, ParameterType must be know all the time when you use CMsgConsistencyTest and when its members access to m_ConsistencyErrors

For that CMsgConsistencyTest can be a template class, example

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

otherwise you may have to do something ugly and catastrophic and 'non C++' like that :

   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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM