0

I have the following function that loops through a vector and get the output of a public member functions. This output is a constant like 1, 8 or 3 etc.

void testItems(const TestObjectList* const testObject) {

              std::vector<ObjectTestFirst> testobjects = testObject->getTestObjects();             
              std::vector<ObjectTestFirst>::iterator itr;
              std::stringstream strbuffer;

              for (itr = testobjects.begin(); itr != testobjects.end(); itr++){
                     strbuffer << tc.toString(itr->getTimest()) << ",\t"
                            << itr->getObjectTest1() << ",\t"
                            << itr->getObjectTest2() << ",\t"
                            << itr->getObjectTest3() << ",\t"
                            << std::endl;
              }
              outfile << strbuffer.str() << std::endl;
}

I have a definition of these constants in a header file that I import (hpp) represented as a enum:

enum TestObjectClass {
    TestObjectClass_Zero = 0,
    TestObjectClass_TestApple = 1,
    TestObjectClass_TestOrange = 8,
    TestObjectClass_TestBanana = 3,
};

In the first code snippet that I show, the testItems function, how do I check the output of the public member function with the enum and print the enum name?

Example: itr->getObjectTest1() << ",\t" outputs 8 - I then check the enum and it match TestObjectClass_TestOrange = 8 so I print out TestObjectClass_TestOrange instead of the constant (8).

Cœur
  • 37,241
  • 25
  • 195
  • 267
JJ Jones
  • 101
  • 1
  • 7
  • Easiest thing to do is to map your `enum` values to strings, you can't directly print your `enum`'s member names. – George Jan 14 '18 at 23:03
  • Please clarify: It looks like you're trying to get an enum name from it's value? If so, everything about for loops and test objects is irrelevant fluff. – Disillusioned Jan 14 '18 at 23:07
  • Is this what you're asking: https://stackoverflow.com/q/11714325/224704 – Disillusioned Jan 14 '18 at 23:12

1 Answers1

1

Unfortunately since there is no generic enum-to-string function in C++11 (maybe C++17 will address this finally?) you have to roll your own.

enum class TestObjectClass : uint16_t
{
    Zero = 0,
    TestApple = 1,
    TestOrange = 8,
    TestBanana = 3,
};

Then you can create this overloaded ostream operator to get your desired behavior.

std::ostream& operator<< (std::ostream& os, TestObjectClass objClass)
{
    switch (objClass)
    {
        case TestObjectClass::Zero: return os << "Zero" ;
        case TestObjectClass::TestApple: return os << "TestApple";
        case TestObjectClass::TestOrange: return os << "TestOrange";
        case TestObjectClass::TestBanana: return os << "TestBanana";
        // omit default case to trigger compiler warning for missing cases
    }
    return os << static_cast<uint16_t>(objClass);
}
Justin Randall
  • 2,243
  • 2
  • 16
  • 23