This question was at the interview: Does this code causes any compile/linking errors and why so?
template <int T> void f();
template <> void f<0>() {}
void test()
{
f<1>();
}
Please explain the behaviour. Thanks a lot.
This question was at the interview: Does this code causes any compile/linking errors and why so?
template <int T> void f();
template <> void f<0>() {}
void test()
{
f<1>();
}
Please explain the behaviour. Thanks a lot.
template<> void f<0>() {}
is specialization of function template for argument 0
, if you call f<0>()
this version of function will be called.
This code is incorrect, it cause linking errors, since there is no specialization for f<1>
and template version of function is not defined
.
template<>
points, that it's full specialization of function.
– ForEveR
May 21 '14 at 9:27
It will compile (all the code is gramatically valid) but will fail at link stage.
This is because template <int T> void f();
is declared but not defined, the <0> specialisation is defined but that makes no odds to you since you're not instantiating it.
Actually, it would be possible for the <0> specialisation to contain syntax errors and the program would still compile without error! This is because formally, templates are only compiled if they are used. (I wouldn't expect a candidate to have the presence of mind during interview conditions to point that out.)
}
syntax error, the compiler may have trouble determining where the function definition was supposed to end, causing it to parse incorrectly down the line.
– Variadicism
Oct 19 '16 at 16:18
It will compile because compiler can see a declaration for a generic template. There is a fully specialized template for 0 also. But we are calling it for 1, which will try to invoke the generic template, but since linker cannot find any definition for the general template, the program will show linker error.
Soloution
template <int T> void f();
template <> void f<0>() {}
template <int T> void f() { }
void test()
{
f<1>();
}
template <int T> void f() { }
– P0W May 21 '14 at 9:24