具有先前模板参数类型的自动返回类型参数的函数类型的模板参数 [英] Template parameters of function type with auto return type arguments of previous template parameter types

查看:55
本文介绍了具有先前模板参数类型的自动返回类型参数的函数类型的模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个参数的模板:第一个是类型,第二个是带有参数的函数指针,其类型是第一个模板参数.此MCVE可以工作:

I have a template with two parameters: the first is a type, and the second is a function pointer with an argument whose type is the first template parameter. This MCVE works:

void returnsVoid(int x) { }

template <typename T, void (*Func)(T)>
struct foo { void bar(T t) { Func(t); } };

int main(int, char *[]) {
    foo<int, returnsVoid> a; // ok
}

但是,当我将第二个模板参数的返回类型更改为 auto 时(如此相关问题中所述),出现错误:

However, when I change the return type of the second template parameter to auto (as explained in this related question), I get an error:

void returnsVoid(int x) { }

template <typename T, auto (*Func)(T)>
struct foo {
    void bar(T t) { Func(t); }
};

int main(int, char *[]) {
    foo<int, returnsVoid> a; // error: unable to deduce ‘auto (*)(T)’ from ‘returnsVoid’
                             // note:   mismatched types ‘T’ and ‘int’
}

为什么这不再适用于 auto 返回类型?

Why does this no longer work with an auto return type?

我正在Ubuntu Linux机器上使用g ++ 9.3.0.铛10中发生了类似的错误.

I'm using g++ 9.3.0 on an Ubuntu Linux machine. A similar error occurs in clang 10.

推荐答案

这是gcc的错误.(错误83417 )

This is gcc's bug. (Bug 83417)

当使用第一个模板参数 T 作为函数参数时,gcc似乎无法推断出 auto 的类型;您可以使用 std :: type_identity (从C ++ 20)将其排除在模板参数推论.

It seems gcc failing deducing the type of auto when using the 1st template parameter T as function parameter; you can use std::type_identity (since C++20) to exclude it from participating in template argument deduction.

// workaround for gcc
template <typename T, auto (*Func)(std::type_identity_t<T>)>
struct foo {
    void bar(T t) { Func(t); }
};

实时

顺便说一句:第10章似乎运行良好.

BTW: Clang 10 seems working well.

这篇关于具有先前模板参数类型的自动返回类型参数的函数类型的模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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