如何从类中获取成员函数的返回类型?

编程入门 行业动态 更新时间:2024-10-24 01:51:37
本文介绍了如何从类中获取成员函数的返回类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下程序会通过 clang 产生编译错误,尽管它会传递给其他编译器:

The following program yields a compilation error with clang, though it passes on other compilers:

#include <utility> struct foo { auto bar() -> decltype(0) { return 0; } using bar_type = decltype(std::declval<foo>().bar()); }; int main() { return 0; }

clang 产生:

$ clang -std=c++11 clang_repro.cpp clang_repro.cpp:10:48: error: member access into incomplete type 'foo' using bar_type = decltype(std::declval<foo>().bar()); ^ clang_repro.cpp:3:8: note: definition of 'foo' is not complete until the closing '}' struct foo ^ 1 error generated.

该程序是否非法?如果是,是否有正确的方法来定义 foo :: bar_type ?

Is this program illegal, and if so, is there a correct way to define foo::bar_type?

clang 详细信息:

$ clang --version Ubuntu clang version 3.5-1ubuntu1 (trunk) (based on LLVM 3.5) Target: x86_64-pc-linux-gnu Thread model: posix

推荐答案

g ++ 4.9问题相同的错误

我不确定这是否是无效代码,因为 declval 允许使用不完整的类型,并且不评估 decltype 中的表达式. rightføld在他的答案中很好地解释了为什么此代码无效.

I'm not sure if this is an invalid code, because incomplete types are allowed for declval, and expression in decltype is not evaluated. rightføld in his answer explained very good why this code is invalid.

您可以使用 std :: result_of :

using bar_type = std::result_of<decltype(&foo::bar)(foo)>::type;

实际上是这样实现的:

using bar_type = decltype((std::declval<foo>().*std::declval<decltype(&foo::bar)>())());

此代码与问题中的代码之间的区别在于,使用了指向成员的指针运算符(.* )而不是成员访问运算符(.),并不需要类型完整,如以下代码所示:

The difference between this and the code in the question is that pointer-to-member operator (.*) is used instead of member access operator (.), and it doesn't require the type to be complete, which is demonstrated by this code:

#include <utility> struct foo; int main() { int (foo::*pbar)(); using bar_type = decltype((std::declval<foo>().*pbar)()); }

更多推荐

如何从类中获取成员函数的返回类型?

本文发布于:2023-07-22 10:33:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1186732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   类中   成员   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!