Why this C++ recursive template didn't work? -
i found interesting question , decided examine top answer in detail.
asked myself why there needs structure , try rewrote code without it:
#include <iostream> template <int n> void out(std::ostream& os) { out<n-1>(os); os << n << std::endl; } template <> void out<1>(std::ostream& os){ os << 1 << std::endl; } int main(){ out<100>(std::cout); }
and tried refactor code. got this:
#include <iostream> template <int n> void out() { if (n != 1) { out<n-1>(); std::cout << n << std::endl; } else { std::cout << 1 << std::endl; } } int main(){ out<100>(); }
i don't understand why code didn't work.
ideas?
the problem if
condition evaluated @ run-time. when instantiation n = 1
, doesn't know first block of if
statement won't execute. proceeds instantiate out<0>
, on. if had static if
, possible, it won't happen soon.
Comments
Post a Comment