complex C++ template syntax
After joining SO, I am frequently seeing this kind of syntax whenever I open topics discussing templates. I tried searching on google, but in vain.
template<typename T>
char (&f(T[1]))[1]; //what is it? what is the use of '[]' brackets and the integer in it?
template<typename T>
char (&f(...))[2]; //not this either
int main() { char c[sizeof(f<void()>(0)) == 2]; } // and this?
From here : SFINAE with invalid function-type or array-type parameters?
Please explain the 3 lines where I have put comments. I particularly want to understand the syntax. Can w开发者_开发知识库e use such syntax in templates only?
The following two are equivalent
// 1
template<typename T>
char (&f(...))[2];
// 2
typedef char rettype[2];
template<typename T>
rettype &f(...);
You may have have seen that pattern before with function pointers
char (*XXX)();
Now just replace the ()
with [N]
to create an array instead of a function part, and replace *
by &
to create a reference instead of a pointer, and replace the XXX
by a function declarator. Then you get a function that returns a reference to an array of size N
.
You may want to look into man signal
, which contains a similarly typed function declaration. If you take out the inner declarator that actually declares the function, you get the same pattern
void (* signal(int sig, void (*func)(int)) )(int);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ take out that
It will return a pointer to a function that takes an int
and returns void
, as described in that manpage.
The following is just a way to yield a compiler error if some condition is not satisfied. If the test foo == 2
turns out to be false
, the array created is of zero size, which is illegal in C++, and will earn a compile time error. If it evaluates to true, nothing happens except the array being declared.
char c[some silly condition here];
精彩评论