Type of Template Parameters (For function Templates) : C++ -
i reading tutorial:
http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/
and mentioned however, template type parameters not type of template parameters available. template classes **(not template functions)** can make use of kind of template parameter known expression parameter.
so wrote program:
#include <iostream> using namespace std; template<typename t,int n> bool compare(t t,const char* c) { if (n != 1) { cout << "exit failure" << endl; exit(exit_failure); } bool result=false; cout << c << endl; cout << t << endl; cout << t.compare(c) << endl; if(t.compare(c) == 0) result = true; return result; } int main() { string name="michael"; if (compare<string,1>(name,"sam")) cout << "it sam" << endl; else cout << "this not sam" << endl; return 0; }
and got output:
$ ./expressionparameter sam michael -1 not sam
clearly, here template parameter taking int n
expression parameter
. point mentioned in tutorial template classes (not template functions) can make use of kind of template parameter known expression parameter.
seems incorrect.
further reading at
also suggest same.
so have understood that: no matter if function template or class template, template parameter template type parameter i.e. typename
or expression parameter
. constraint , expression parameter - must constant integral expression
. compiler not differentiate if function
or class
.
is understanding correct?
yes, seem understand correctly.
one use case of write generic code still benefits of compile-time constant (such better compiler optimizations).
one example std::array, takes such template size_t
parameter length. example std::enable_if, uses bool
.
Comments
Post a Comment