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


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -