繁体   English   中英

模板参数类型(对于功能模板):C ++

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

我正在阅读本教程:

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

有人提到, 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.

所以我写了一个程序:

#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;
    }

并得到输出:

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

显然,这里的模板参数将int n作为expression parameter 因此,教程Template classes (not template functions) can make use of another kind of template parameter known as an expression parameter.提到的要点Template classes (not template functions) can make use of another kind of template parameter known as an expression parameter. 似乎是不正确的。

进一步阅读

非类型模板参数

也建议一样。

所以我了解的是:无论是函数模板还是类模板,模板参数都可以是template type parameter ie typenameexpression parameter 唯一的限制是,对于表达式参数-它必须是constant integral expression 编译器不区分是用于function还是用于class

我的理解正确吗?

是的,您似乎正确理解了这一点。

这样的一个用例是编写通用代码,但仍然可以获得编译时常量的好处(例如更好的编译器优化)。

一个示例是std :: array ,其长度采用这样的模板size_t参数。 另一个示例是std :: enable_if ,它使用bool

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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