如何在模板参数中使用>(大于)而不出现解析错误?

How to use > (greater-than) inside a template parameter and not get a parsing error?

本文关键字:大于 错误 参数 gt      更新时间:2023-10-16

我只想根据模板参数的大小定义一个函数:

template <class T>
typename std::enable_if<sizeof(T) > 1, void>::type
foobify(T v) {
    // ...
}
int main() {
    //foobify((unsigned char)30); // should not compile
    foobify((long)30);
}

然而,我得到:

main.cpp:8:41: error: expected unqualified-id before numeric constant
     typename std::enable_if<sizeof(T) > 1, void>::type

如果我改为1 < sizeof(T),它会起作用。因此,我相信GCC认为我正在结束模板参数,而不是继续布尔表达式。

有没有什么方法可以使用>本身而不必处理它?

是的,使用该运算符的表达式必须加括号。参见[临时名称]/3:

当解析模板参数列表时,将第一个非嵌套的>138作为结束分隔符而不是大于运算符[..][示例:

template<int i> class X { /* ...*/ };
X< 1>2 > x1; // syntax error
X<(1>2)> x2; // OK

-结束示例]

138)一个包含dynamic_caststatic_castreinterpret_castconst_cast类型id>,或包含后续模板id的模板参数s被认为是嵌套的

显然,如果您使用该比较的对称对应项,即使用<,则这并不适用——在这种情况下,解析是明确的。

是的,您应该使用括号:

template <class T>
typename std::enable_if<(sizeof(T) > 1), void>::type
foobify(T v) {
    // ...
}

对于C++20,

template<class T>
requires (sizeof(T) > 1)
void foobify(T v) {
    // ...
}
int main() {
//  foobify((unsigned char)30); // should not compile
    foobify((long)30);
}