如何从类中获取成员函数的返回类型? [英] How to get the return type of a member function from within a class?
问题描述
以下程序会通过 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
推荐答案
我不确定这是否是无效代码,因为 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)());
}
这篇关于如何从类中获取成员函数的返回类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!