我可以写一个函数类型返回一个函数? [英] Can I write a function type that returns a function?

查看:221
本文介绍了我可以写一个函数类型返回一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法在gcc和clang上编译以下内容

The following fails to compile on both gcc and clang

#include <type_traits>

int foo();

int main()
{
    using R = std::result_of_t<decltype(foo)()>; // error
}

两个编译器上的错误都涉及到声明函数的非法性返回一个函数。但我不是声明这样的函数 - 我只是想写它的类型,因为这是 result_of 期望。这是真的还是不成形?

The error on both compilers deals with the illegality of declaring a function returning a function. But I'm not declaring such a function - I'm just trying to write its type - since that's what result_of expects. Is this really still ill-formed?

推荐答案

您正在传递 type-id http://eel.is/c++draft/dcl.namerel =nofollow> [dcl.name] 为

You're passing a type-id, which is defined in [dcl.name] as


[...]语法上的一个类型的变量或函数的声明,省略实体的名称。 [...]如果构造是声明中的声明符,则可以在抽象声明符中标识符将出现的位置。该命名类型与
假设标识符的类型相同。

有某种类型,假设的声明必须在第一位形成良好。但它不是每 [dcl.fct] / 10 。因此,程序是不成形的(并且编译器的错误消息实际上是可理解的)。这种情况也更直接地由 [temp.deduct] /(8.10),表示这是一个(SFINAE友好)错误。

For the hypothetical identifier to have some type, the hypothetical declaration must be well-formed in the first place. But it isn't as per [dcl.fct]/10. Hence the program is ill-formed (and the compilers' error messages are actually comprehensible). This case is also more directly covered by [temp.deduct]/(8.10), implying that this is a (SFINAE-friendly) error.

事实上,仅仅意味着无效类型的使用足够使程序错误。例如。创建函数返回函数的类型指针是错误的:

In fact, merely implying an invalid type's usage suffices to make the program ill-formed. E.g. creating the type pointer to function returning function is ill-formed:

using f = int();
using t = f(*)();

下面是:

struct A {virtual void f() = 0;};
using t = A(*)();

(Clang不应该接受这个。Cf GCC错误 17232 的有趣讨论)。

(Clang shouldn't be accepting this. C.f. GCC bug 17232's interesting discussion).

这篇关于我可以写一个函数类型返回一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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