Complex C ++ Template Syntax

After joining SO, I often see this syntax when I open topics that discuss patterns. 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? 

Hence: SFINAE with invalid type parameters of type or array?

Please explain the 3 lines where I posted the comments. I especially want to understand the syntax. Can we use this syntax only in templates?

+4
source share
1 answer

Next two equivalents

 // 1 template<typename T> char (&f(...))[2]; // 2 typedef char rettype[2]; template<typename T> rettype &f(...); 

You may have already seen this template with function pointers.

 char (*XXX)(); 

Now just replace () with [N] to create an array instead of part of the function, and replace * with & to create a link instead of a pointer, and replace XXX with the declarator function. Then you get a function that returns a reference to an array of size N


You might want to look into the man signal , which contains a similarly typed function declaration. If you select an internal declarator that will actually declare the function, you will get the same template

 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 this man page.


Below is only a way to get a compiler error if any condition is not met. If the test foo == 2 turns out to be false , the created array has a zero size, which is illegal in C ++ and will cause a compile-time error. If it evaluates to true, nothing happens except the declared array.

 char c[some silly condition here]; 
+4
source

All Articles