参考以下代码:
#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;
}
为什么我必须首先在 bitwise
列表中指定参数 template
?编译器可以从函数 arg 中推导出 T 那么为什么在这种情况下 bitwise
需要是第一个?
答案 0 :(得分:4)
是因为这个电话:
cout << func<true>(7,1) << endl;
这会使用 true
作为其第一个(也是唯一的)模板参数来实例化模板。
在实例化模板时,任何显式模板参数都会分配给模板声明中的初始参数和任何剩余的< /em> 参数必须是可推导的。这几乎将给定的模板参数顺序(在模板声明中)作为唯一有效的顺序。