Why am I not getting compiler errors from returning from the void function template?

Consider:

void f() { return 5; } 

The above will cause errors. But why not this ?:

 template <typename = void> void f() { return 0; } 

I am compiling gcc-4.5.1. Why does it matter using templates so that I don't get errors from executing the same illegal return statement as a function without a template ?. The only thing I get is that I cannot call the function (ie f() ) without getting:

error: return-statement with a value, in function returning 'void'

But still, what could be the reason that I can define a return statement for the void function template?

Here is the code I have:

 template <typename = void> void f() { return 0; } // pass int main() { } 

The above code will pass despite the supposedly illegal return statement in the function returning void.

+4
source share
3 answers

This is a performance issue. Specific quote from the standard:

14.6 / 8 [...] If a valid specialization cannot be created for a template definition and this template is not created, the template definition is poorly formed, diagnostics are not required. [...]

That is, your program is poorly formed because this template cannot be used to create any valid specialization, but the compiler is not required to diagnose this. When you later create an instance of the template, the compiler must generate a specialization, this specialization is invalid and the compiler complains.

You will not get an error in the definition of the template, because the compiler monitors the absence of a diagnostic path, i.e. ignores the problem until it can no longer ignore it in the instance.

+6
source

Most checks are performed only when creating a template.

This is usually good, as the code may work fine with one template argument, but not compile it with another. If you have a template overload, the compiler even ignores candidates that cannot compile, see SFINAE .

+10
source

You do :

 template <typename = void> void f() { return 0; } int main() { f<int>(); } 

prog.cpp: In the function 'void f () [with = int]':
prog.cpp: 7: 12: created here
prog.cpp: 2: 12: error: return-statement with value, in function returning 'void'

Although the program is still poorly formed, the compiler chooses not to diagnose a semantic error (which is its prerogative) because you never create this function.

+7
source

Source: https://habr.com/ru/post/1243109/


All Articles