c++ - Conditional compilation and non-type template parameters -
i having trouble understanding non-type template arguments , hoping shed light on this.
#include <iostream> template<typename t, int a> void f() { if (a == 1) { std::cout << "hello\n"; } else { t("hello"); } } int main() { f<int, 1>; }
when compile this, error saying:
/tmp/conditional_templates.cc:13:12: required here /tmp/conditional_templates.cc:8:5: error: cast ‘const char*’ ‘int’ loses precision [-fpermissive] t("hello"); ^
but, can't compiler detect non-type argument "a" 1 , hence else branch won't taken? or expect? in case, how accomplish this?
try instead:
#include <iostream> template<typename t, int a> struct { void f() { t("hello"); } }; template<typename t> struct a<t,1> { void f() { std::cout << "hello\n"; } }; int main() { a<int,1> a; a.f(); a<int,2> b; b.f(); }
now, uses partial template specialization in order provide alternative implementations specific values of template parameters.
note i've used class, because function templates cannot partially specialized