簡體   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