简体   繁体   中英

Type of Template Parameters (For function Templates) : C++

I was reading this tutorial:

http://www.learncpp.com/cpp-tutorial/144-expression-parameters-and-template-specialization/

and it was mentioned However, template type parameters are not the only type of template parameters available. Template classes **(not template functions)** can make use of another kind of template parameter known as an expression parameter. However, template type parameters are not the only type of template parameters available. Template classes **(not template functions)** can make use of another kind of template parameter known as an expression parameter.

So I wrote a 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 is Sam" << endl;
    else
    cout << "This is not Sam" << endl;
    return 0;
    }

And got the Output:

$ ./ExpressionParameter
Sam
Michael
-1
This is not Sam

Clearly, here the template parameter is taking int n as expression parameter . So the point mentioned in the tutorial Template classes (not template functions) can make use of another kind of template parameter known as an expression parameter. seems to be incorrect.

Further reading at

Non-type template parameters

also suggest the same.

So what I have understood is that: no matter if it is function template or class template, the template parameter could be template type parameter ie typename or expression parameter . The only constraint is that , for expression parameter - it must be constant integral expression . The compiler does not differentiate if it is for function or class .

Is my understanding correct?

Yes, you seem to understand this correctly.

One use case of this is to write generic code but still get the benefits of a compile-time constant (such as better compiler optimizations).

One example is std::array , which takes such a template size_t parameter for its length. Another example is std::enable_if , which uses a bool .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM