3 ms·
The original purpose of SFINAE is to solve a critical problem--if you have multiple template versions of a function available, they don't all have to be valid f
by zeroonetwothree 11y ago
The original purpose of SFINAE is to solve a critical problem--if you have multiple template versions of a function available, they don't all have to be valid for a given call. For example say you want to have a "first" operator that takes the first item of a container, but also works on individual values if they aren't containers:
template<class Container>
Container::value_type first(Container&& c) {
return *c.begin();
}
template<class ValueType>
ValueType first(ValueType&& vt) {
return vt;
}
// Usage:
first<int>(1); // 1
This call doesn't cause a compile error even though int::value_type does not exist--this is SFINAE. To make this work properly you'd also need to use compile-time introspection to disable the second function for types that have value_type, otherwise it's ambiguous.
- weland 11y ago> For example say you want to have a "first" operator that takes the first item of a container, but also works on individual values if they aren't containers: But why would I want to do such a thing? Not only does first() not make sense for non-container objects -- but calling x.first() when x is a non-container object is a bug 9 times out of 10 (i.e. something got unpacked when it shouldn't have, an [x] (a single-object vector) ended up x (i.e. the first and only value of that vector).
- MichaelGG 11y agoSFINAE looks like a cheap way to sort of hack around lack of static duck typing. Otherwise these examples could be written in a positive way by saying a certain function only applies to a type containing certain members or constraints.