PaulProgrammerNoob PaulProgrammerNoob - 24 days ago 10
C++ Question

Compare variadic arguments by value

Is there a way to compare the values of each type of a variadic template?

template<typename... S>
class Signature {
// this is not valid syntax
S... values;

bool equals(S... s) {
// this is not either
bool eq = true;
eq &= s... &= values...;
return eq;
}
};


Example:

Signature<int, bool> s(5, true);
s.equals(5, true); // should result in 1

Answer Source

This:

S... values;

is ill-formed. You cannot have a pack declaration like that (unfortunately). You have to put all the values in something, like:

std::tuple<S...> values;

And once you do that, comparing them is simple. Just use ==:

template<typename... S>
struct Signature {
    std::tuple<S...> values;

    bool equals(Signature<S...> const& rhs) const {
        return values == rhs.values;
    }

    bool equals(S const&... rhs) const {
        // forward here to produce a tuple<S const&...> and avoid an unnecessary copy
        return values == std::forward_as_tuple(rhs...);
    }
};