在类模板特化中使用sizeof模板参数包

Using sizeof template parameters pack in class template specialization

本文关键字:参数 sizeof 类模板特化      更新时间:2023-10-16

GCC上编译以下代码(根据从右到左1的索引从类型列表中选择类型的元函数)的正确性检查失败,而clang接受此代码:

#include <cstdlib>
template< std::size_t i, typename ...types >
struct at_index
{
};
template< typename first, typename ...rest >
struct at_index< (1 + sizeof...(rest)), first, rest... >
{
    using type = first;
};
template< std::size_t i, typename first, typename ...rest >
struct at_index< i, first, rest... >
        : at_index< i, rest... >
{
}; 
int main()
{
}

哪个编译器是正确的?

GCC错误信息:

error: template argument '(1 + sizeof... (rest))' involves template parameter(s)
 struct at_index< (1 + sizeof...(rest)), first, rest... >
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我认为sizeof...操作符中参数包的类型不应该被解析为符号名的某些部分。因此,这里应该没有名称混淆的问题。

这是一个clang扩展来允许上面的代码吗?

N4140 [temp.class.spec]/8.1:

部分专门化的非类型参数表达式不能包含部分专门化的模板参数,除非参数表达式是一个简单的标识符

这已经被核心问题1315放宽了。大概GCC还没有开始实现它。