struct C
{
int Foo(int i) { return i; }
typedef decltype(C::Foo) type;
};
Since there is no such type as a member function type (there isn't, is there?), I expect C::type
to be int (int)
.
But the following won't compile using the Visual C++ 2012 RC:
std::function<C::type> f;
So what type is decltype(C::Foo)
?
The code is ill-formed: there are only a few ways that a member function name (e.g. C::Foo
) can be used, and this is not one of them (the complete list of valid uses can be found in the C++ language standard, see C++11 §5.1.1/12).
In the context of your example, the only thing you can really do is take the address of the member function, &C::Foo
, to form a pointer to the member function, of type int (C::*)(int)
.
Since the code is ill-formed, the compiler should reject it. Further, it yields inconsistent results depending on how C::Foo
is used; we'll look at the inconsistency below.
Please report a bug on Microsoft Connect. Alternatively, let me know and I am happy to report the issue.
If you have a type but you don't know what the type is, you can find out the name of the type by using it in a way that causes the compiler to emit an error. For example, declare a class template and never define it:
template <typename T>
struct tell_me_the_type;
Then later, you can instantiate this template with the type in which you are interested:
tell_me_the_type<decltype(C::Foo)> x;
Since tell_me_the_type
hasn't been defined, the definition of x
is invalid. The compiler should include the type T
in the error it emits. Visual C++ 2012 RC reports:
error C2079: 'x' uses undefined struct 'tell_me_the_type_name<T>'
with
[
T=int (int)
]
The compiler thinks that C::Foo
is of type int (int)
. If that is the case, then the compiler should accept the following code:
template <typename T>
struct is_the_type_right;
template <>
struct is_the_type_right<int(int)> { };
is_the_type_right<decltype(C::Foo)> x;
The compiler does not accept this code. It reports the following error:
error C2079: 'x' uses undefined struct 'is_the_type_right<T>'
with
[
T=int (int)
]
So, C::Foo
both is of type int (int)
and is not of type int (int)
, which violates the principle of noncontradiction. :-)
So what type is
decltype(C::Foo)
?
It's no type, since using just C::Foo
is ill-formed.
来源:https://stackoverflow.com/questions/11354841/decltype-and-member-function-not-pointer-type