Consider:
void f() {
return 5;
}
The above will raise errors. But why not this?:
template <typename = void> void f() {
return 0;
}
I'm compiling with gcc-4.5.1. Why does it make a difference using templates such that I wouldn't receive errors from doing the same illegal return statement as a non-template function?. The only setback I get is that I can't call the function (i.e f()
) without getting:
error: return-statement with a value, in function returning 'void'
But still, what could be the reason that I am able to define a return statement for a 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 a presumably illegal return statement in a function returning void.
Most of the checks are only done when you instantiate the template.
This is usually a good thing, as a code could work fine with one kind of template argument but fail to compile with another one. If you have template overloading, the compiler will even ignore candidates that fail to compile, see SFINAE.
You do:
template <typename = void> void f() {
return 0;
}
int main()
{
f<int>();
}
prog.cpp: In function 'void f() [with = int]':
prog.cpp:7:12: instantiated from here
prog.cpp:2:12: error: return-statement with a value, in function returning 'void'
Though the program is still ill-formed, the compiler is choosing not to diagnose the semantic error (which is its prerogative) because you're never actually instantiating that function.
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