What to call the expression `T (&some(...)) [2]` where T=char
Asked Answered
U

1

8

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)

Unconformable answered 16/6, 2018 at 14:43 Comment(0)
S
13

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.
Sinuate answered 16/6, 2018 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.