Why does “&& true” added to a constraint make a function template a better overload?

26

Consider the following two overloads of a function template foo:

template <typename T>
void foo(T) requires std::integral<T> {
    std::cout << "foo requires integral\n";
}

template <typename T>
int foo(T) requires std::integral<T> && true {
    std::cout << "foo requires integral and true\n";
    return 0;
}

Note the difference between the two constraints: the second has an extra && true.

Intuitively speaking, true is redundant in a conjunction (since X && true is just X). However, it looks like this makes a semantic difference, as foo(42) would call the second overload.

Why is this the case? Specifically, why is the second function template a better overload?

Share
Improve this question
7
  • 1
    It's "more specialized". There are more requirements, so it's narrower, so it's "better". – NathanOliver Apr 8 at 14:39
  • 6
    So, would adding && !false make it even better? – Adrian Mole Apr 8 at 14:40
  • 2
    AFAIK, the standard doesn't really care what it does, just that there are more requirements. – NathanOliver Apr 8 at 14:41
  • 1
    @AdrianMole Looks like the answer is no: godbolt.org/z/j6hG98WEv – Meowmere Apr 8 at 14:50
  • 3
    It falls out of the rules. There's not really motivation to add a special case for this. – T.C. Apr 8 at 14:56

Comments

Popular posts from this blog

Meaning of `{}` for return expression

Get current scroll position of ScrollView in React Native

React Native - Image Cache