I just started to understand some template basics. Actually, until now I just accepted it as a fact, but I dont really understand the reason why this is broken:
template <typename T,bool hasFoo>
struct Broken {
void foobar(){
if (hasFoo){T::foo();}
else { std::cout << "BROKEN" << std::endl;}
}
};
int main(){
Broken<int,false> t;
t.foobar();
}
while this works:
template <typename T>
struct Works {
void foo(){T::foo();}
void bar(){std::cout << "WORKS" << std::endl;}
};
int main(){
Works<int> t;
t.bar();
}
Somehow it is obvious, but I just want to make sure that I am not missing something:
Does this work, because if the function Works<int>::foo()
is never called, it simply does not get instantiated?
PS: To avoid misunderstandings: I know, why Broken
is broken and I recently had a question related to this where I got good answers, however after that I thought that also Works<int>
should not compile until I accidentally passed a "wrong" template parameter and was surprised that it did compile.