如何在C++模板中使用比较表达式

How to use comparison expressions in C++ templates?

本文关键字:比较 表达式 C++      更新时间:2023-10-16
#include <type_traits>
template<int n>
std::enable_if_t<n == 1, int> f() {}
// OK
template<int n>
std::enable_if_t<n > 1, int> g() {} 
// VS2015 : error C2988: unrecognizable template declaration/definition
int main()
{}

我知道错误是由于编译器将"大于"符号">"作为模板终止符号。

我的问题是:在这种情况下,如何使比较表达合法?

将表达式放在括号中:

#include <type_traits>
template<int n>
std::enable_if_t<(n == 1), int> f() { }
template<int n>
std::enable_if_t<(n > 1), int> g() { } 
int main() { }