Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

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.

like image 563
David G Avatar asked Nov 29 '22 16:11

David G


2 Answers

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.

like image 197
Karoly Horvath Avatar answered Dec 01 '22 07:12

Karoly Horvath


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.

like image 38
Lightness Races in Orbit Avatar answered Dec 01 '22 06:12

Lightness Races in Orbit