[英]Default template function argument
參考以下代碼:
#include <iostream>
#include <variant>
#include <limits>
using namespace std;
template < bool bitwise = false, typename T>
// template <typename T, bool bitwise = false>
// ^ wont work! error: no matching function for call to 'func<true>(int, int)'
bool func(T a, T b) {
if constexpr(bitwise) {
return a & b;
}
else {
return a && b;
}
}
int main()
{
cout << func(7,1) << endl;
cout << func<true>(7,1) << endl;
}
為什么我必須在template
列表中首先bitwise
指定參數? 編譯器可以從 function arg 中推斷出 T 那么為什么在這種情況下bitwise
需要成為第一個呢?
這是因為這個電話:
cout << func<true>(7,1) << endl;
這將使用true
作為其第一個(也是唯一的)模板參數來實例化模板。
實例化模板時,任何顯式模板參數都分配給模板聲明中的初始參數,並且任何剩余參數必須是可推導的。 這幾乎將給定的模板參數順序(在模板聲明中)作為唯一有效的順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.