如何在模板参数中使用>(大于)而不出现解析错误?
How to use > (greater-than) inside a template parameter and not get a parsing error?
我只想根据模板参数的大小定义一个函数:
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_cast
、static_cast
、reinterpret_cast
或const_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);
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- 为什么C++在乘以大于 590x590 大小的矩阵时出现分割错误?
- 向量下标出的范围错误.即使向量的索引大于访问数据的索引,也会发生误差
- 大于1000000时,Eratosthenes错误的CUDA筛子
- sin cos 函数在大于 90 的度数时给出错误的结果
- C :创建大于大小的数组索引,不会引起错误
- 对于大于 4GiB 的文件,fread 有时会返回错误的值
- 如何在模板参数中使用>(大于)而不出现解析错误?
- 当我想要大于1000000的质数时,下面的质数生成器代码显示了一个错误
- 在 std::sort() 中的自定义函数中,>(大于)运算符与 <(小于运算符)的交换会导致分段错误吗?
- 如果从文件中创建的地形大于128*128,则会产生堆栈溢出错误
- 大于1GB内存分配错误
- vector大小错误,大于元素数