I've seen this expression in a library implementation and I basically understand it is been used to foster SFINAE or even to pull the static_assert
trigger.
It basically takes the form:
template <typename>
char (&checkValid(...))[2];
template <typename T>
char checkValid(e); where e is an expression(using type T) results in type X
If e
is well-formed then the result will be (assuming the usage of sizeof
) 1 else 2 and can be applied in:
static_assert(sizeof(checkValid<T>(0))==1,"") ;
The other day I've been doing something similar in a different way:
using namespace std;
template<typename...T>
using isValid = void;
template<typename>
false_type checkValid(...);
template<typename T>
true_type checkValid(isValid<typename T::type>*);
struct some{
using type = int;
};
int main(){
constexpr bool result = decltype(checkValid<some>(0))::value;
}
Regardless of what I've done and what I saw, I am more curious about knowing:
What is this expression called?
template <typename>
char (&checkValid(...))[2];
"Variable template"? "Function template?" Or "an array taking the reference to ..."? (sorry if my guess is awful)
What are Terms in an Expression? A term can be a number, a variable, product of two or more variables or product of a number and a variable. An algebraic expression is formed by a single term or by a group of terms. For example, in the expression 4x + y, the two terms are 4x and y.
Function expressions are when you create a function and assign it to a variable. The function is anonymous, which means it doesn't have a name. For example: let myFunction = function() { // do something }; As you can see, the function is assigned to the myFunction variable.
The definition of a variable expression is a mathematical "phrase" that contains variables and numbers combined together with any mathematical operations. Some examples of variable expressions are: x - in this expression, x is the variable, and there are no other numbers or operations.
Coefficient: The numerical factor of a multiplication expression that contains a variable.
It's a function template, returning a reference to char[2]
.
checkValid // `checkValid` is
checkValid(...) // a function with (...) parameter list, returning
&checkValid(...) // a reference to
(&checkValid(...)) // (discard parentheses)
(&checkValid(...))[2] // an array of 2
char (&checkValid(...))[2] // characters.
template <typename> char (&checkValid(...))[2]; // And it's a template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With