模板化lambda的显式实例化 [英] Explicit instantiation of templated lambda

查看:58
本文介绍了模板化lambda的显式实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚遇到一个问题,需要显式实例化模板化的lambda.下面的代码无法编译,但是在这种情况下我无法弄清楚出了什么问题:

I just came across a problem to explicit instantiate a templated lambda. The below code does not compile, but I can't figure out what's wrong in this case:

        [&]<auto... II>(std::index_sequence<II...>) {
            auto check = [&]<auto I>(){
            };
            (check<II>(),...);
        }(std::make_index_sequence<N>{});

编译器错误(gcc主干:11.0.0):

Compiler error (gcc trunk: 11.0.0):

rswitch.cc: In lambda function:
rswitch.cc:42:28: error: expected primary-expression before ')' token
42 |                 (check<II>(),...);
|                            ^
rswitch.cc:42:26: error: binary expression in operand of fold-expression
42 |                 (check<II>(),...);

我看起来必须像这样使用模板消除歧义:

I looks like I had to use the template disambiguation like this:

        [&]<auto... II>(std::index_sequence<II...>) {
            auto check = [&]<auto I>(){
            };
            (this->template check<II>(),...);
        }(std::make_index_sequence<N>{});

还有其他表达方式吗?

推荐答案

check 本身不是模板.这是一个未指定关闭类型的对象,包含

check itself is not a template. It is an object, of an unspecified closure type, that contains

template<auto I> void operator()();

成员函数是模板.

该错误是由于尝试向 check 提供模板参数而引起的.再次,这本身不是模板.lambda函数调用运算符的模板参数必须是可推导的(即使已命名),函数调用语法才能起作用.C ++ 20并没有改变.

The error is due to the attempt at supplying template arguments to check. Which is not a template itself, again. The template parameters of a lambda's function call operator need to be deducible (even if they are named), for the function call syntax to work. That hasn't changed with C++20.

显式指定参数的唯一方法是丑陋的

The only way to specify the parameters explicitly is the pretty ugly

check.template operator()<II>()

但是相反,使其可推论可能更好.

But instead it may be better to make it deducible.

[&]<auto... II>(std::index_sequence<II...>) {
    auto check = [&]<auto I>(std::integral_constant<decltype(I), I>){
    };
    (check(std::integral_constant<decltype(II), II>{}),...);
}(std::make_index_sequence<N>{});

明确指定 size_t 也是一种选择,而不是使用 decltype(I).

Specifying size_t explicitly is also an option instead of using decltype(I).

这篇关于模板化lambda的显式实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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