g ++和clang ++都被模板函数参数包扩展所困扰? [英] g++ and clang++ are both bugged with template function parameter pack expansion?

查看:114
本文介绍了g ++和clang ++都被模板函数参数包扩展所困扰?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是另一个问题的后续内容答案指出我对模板[temp.param] 17.1.17的关注(最新的C ++ 17草案,但我想也是在前面的标准化中),

This is a follows up of another question where an answer point my attention to Templates [temp.param] 17.1.17 (last C++17 draft, but I suppose also preceding standardizations) where is stated that

作为包扩展的模板参数包不应扩展在同一template-parameter-list中声明的参数包.

A template parameter pack that is a pack expansion shall not expand a parameter pack declared in the same template-parameter-list.

带有此限制的示例

template <class... T, T... Values> // error: Values expands template type parameter
struct static_array;               // pack T within the same template parameter list

因此,如果我正确理解此规则,则以下功能(我认为非常合理)是非法的

So, if I understand correctly this rule, the following function (that I find extremely reasonable) is illegal

template <typename ... Types, Types ... Values>
void foo (std::integral_constant<Types, Values>...)
 { ((std::cout << Values << std::endl), ...); }

因为第二个参数包(Types ... Values)展开了在相同模板参数列表中声明的参数包(Types).

because the second parameter pack (Types ... Values) expand a parameter pack (Types) declared in the same template parameter lists.

无论如何,无论是g ++(例如,9.2.0)还是clang ++(例如,8.0.0)都可以毫无问题地编译以下代码

Anyway, both g++ (9.2.0, by example) and clang++ (8.0.0, by example) compile the following code without problem

#include <iostream>
#include <type_traits>

template <typename ... Types, Types ... Values>
void foo (std::integral_constant<Types, Values>...)
 { ((std::cout << Values << std::endl), ...); }

int main()
 {
   foo(std::integral_constant<int, 0>{},
       std::integral_constant<long, 1L>{},
       std::integral_constant<long long, 2LL>{});
 }

所以我想我有些误会.

g ++和clang ++是否都出错了,还是我误解了标准?

Are both g++ and clang++ bugged or am I that misunderstand the standard?

推荐答案

这是非法的,标准很明确.就其价值而言,MSVC似乎不接受该代码( https://godbolt.org/z/DtLJg5 ).这是一个GCC错误,也是一个 Clang错误. (我没有检查旧版本.)

It's illegal, the standard is very clear. For what it's worth, MSVC doesn't seem to accept the code (https://godbolt.org/z/DtLJg5). This is a GCC bug and a Clang bug. (I didn't check old versions.)

作为解决方法,您可以执行以下操作:

As a workaround, you can do something like this:

template <typename... ICs>
std::enable_if_t<std::conjunction_v<is_integral_constant<ICs>...>> foo(ICs...)
{
    ((std::cout << ICs::value << '\n'), ...);
}

实时演示

这篇关于g ++和clang ++都被模板函数参数包扩展所困扰?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆