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

标签 c++ parsing templates

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

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 认为我正在结束模板参数,而不是继续 bool 表达式。

有什么方法可以使用>自己而无需解决它?

最佳答案

是的,使用该运算符的表达式必须加括号。见 [temp.names]/3:

When parsing a template-argument-list, the first non-nested >138 is taken as the ending delimiter rather than a greater-than operator. [..] [ Example:

template<int i> class X { /* ...*/ };

X< 1>2 > x1; // syntax error
X<(1>2)> x2; // OK

— end example ]

138) A > that encloses the type-id of a dynamic_cast, static_cast, reinterpret_cast or const_cast, or which encloses the template-arguments of a subsequent template-id, is considered nested for the purpose of this description.

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

关于c++ - 如何在模板参数中使用 >(大于)而不出现解析错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423702/

相关文章:

c++ - 如何为STL容器指定模板函数?

c++ - 如何从元组创建元组?

c++ - 如何让调试 C++ 在 Mac 上的 VSCode 中工作?

c++ - 如何从 elf 文件的节标题中提取所有字段?

c++ - cpp 通过引用传递

java - 如何使用作业对象数组? (Jni)

Python:将耗时(分:秒)解析为秒

php - 如何通过 PHP 和 String 函数获取所有 TD 值

c++ - 模板: class specialization

c++ - MSVC 2017 是否支持具有自动矢量化功能的 AVX 512?