Kevin
Kevin

Reputation: 840

C++ Store Differences Between 2 Class Objects

I want to store the differences between two objects of the same class. I know that i can overwrite the operator== to compare two objects.

I now want to know if there is a nicer way to get the differences between two objects than in the following example:

class ExampleClass {
public:
    ExampleClass();

    friend std::vector<std::string> compare(const ExampleClass& other) {
        std::vector<std::string> result;
        if(attribute1_ != other.attribute1_) {
            result.push_back("attribute1_");
        }
        // continue for other attributes
        return result;
    }

private:
    std::string attribute1_;
    int attribute2_;

}

In that example i had to compare each attribute.

Upvotes: 0

Views: 76

Answers (1)

sklott
sklott

Reputation: 2859

I'm not a template guy, so I will show how macro can be used to simplify your task.

First you define macro something like this:

#define COMP_ATTR(attr) \
    if (attr != other.attr) { \
        result.push_back(#attr); \
    }

Then you can rewrite you compare function like this:

friend std::vector<std::string> compare(const ExampleClass& other) {
    std::vector<std::string> result;
    COMP_ATTR(attribute1_);
    // continue for other attributes
    return result;
}

Upvotes: 1

Related Questions