HC4*_*ica 17 c++ member-functions decltype c++11
以下代码:
struct A
{
int f(int);
auto g(int x) -> decltype(f(x));
};
Run Code Online (Sandbox Code Playgroud)
无法编译错误:
error: cannot call member function 'int B::f(int)' without object
Run Code Online (Sandbox Code Playgroud)
如果我将其更改为:
struct A
{
int f(int);
auto g(int x) -> decltype(this->f(x));
};
Run Code Online (Sandbox Code Playgroud)
我收到另一个错误:
error: invalid use of 'this' at top level
Run Code Online (Sandbox Code Playgroud)
这些都有什么问题?我正在使用gcc 4.6
Ton*_*nyK 12
这是神奇的话:
struct A
{
int f(int);
auto g(int x) -> decltype((((A*)0) ->* &A::f)(x)) ;
};
Run Code Online (Sandbox Code Playgroud)
编辑我从Mikael Persson的回答中看到,这就是它在提升方面的表现.
result_of和decltype组合可以给出成员函数的返回类型
#include <type_traits>
using namespace std;
struct A
{
int f(int i) { return i; }
auto g(int x) -> std::result_of<decltype(&A::f)(A, int)>::type
{
return x;
}
};
int main() {
A a;
static_assert(std::is_same<decltype(a.f(123)),
decltype(a.g(123))>::value,
"should be identical");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Comeau不喜欢auto作为顶级返回类型,但以下编译成功:
template <typename R, typename C, typename A1> R get_return_type(R (C::*)(A1));
struct A
{
int f(int);
decltype(get_return_type(&A::f)) g(int x);
};
Run Code Online (Sandbox Code Playgroud)
基本上,您必须声明至少一个可以获得所需类型的其他构造.并decltype直接使用.
编辑:顺便说一句,这适用于潜入成员函数的返回类型:
template <typename R, typename C, typename A1> R get_return_type(R (C::*)(A1));
struct B { int f(int); };
struct A
{
int f(int);
B h(int);
decltype(get_return_type(&A::f)) g(int x);
decltype(get_return_type(&A::h).f(0)) k(int x);
};
int main()
{
return A().k(0);
}
Run Code Online (Sandbox Code Playgroud)
当然,它没有相同的便利性auto f()-> ...,但至少它编译.