Home > Mobile >  Is there a C STL function to compare a value against a compile-time constant?
Is there a C STL function to compare a value against a compile-time constant?

Time:04-28

I've implemented the following function in a utility library:

template <auto Value>
bool equals_constant(const decltype(Value)& value) { return Value == value; }

It's useful with other template functions which take an invocable predicate, like this:

template <auto IsValid>
struct Validator {
    bool validate(int value) { return IsValid(value); }
};

// this validator requires its value to equal 42 (just for demo purposes)
Validator<equals_constant<42>> validator;
std::cout << validator.validate(41) << std::endl; // 0
std::cout << validator.validate(42) << std::endl; // 1

Have I reinvented the wheel - is something like my equals_constant() already in the STL? (If so, I can't find it on cppreference or Google.) Thanks.

CodePudding user response:

No. std isn't a place where "anything vaguely useful" gets put.

boost::hana::equal.to looks to be similar.

  • Related