简体   繁体   中英

Why don't I get compiler errors from returning from a void function template?

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 (ie 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.

This is a quality of implementation issue. The particular quote from the standard would be:

14.6/8 [...] If no valid specialization can be generated for a template definition, and that template is not instantiated, the template definition is ill-formed, no diagnostic required. [...]

That is, your program is ill formed because that template cannot be used to generate any valid specialization, but the compiler is not required to diagnose this. When at a later time you instantiate the template, the compiler must generate the specialization, that specialization is not valid and the compiler complains.

You don't get an error in the template definition because the compiler is following the no diagnostic required path, ie ignoring the problem until it can no longer ignore it in the instantiation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM