Check existence of a member function in C++11
Today, I am revisiting the problem of check existence of a member function
(several posts can be found online). One implementation which inspires me
is What is decltype with two arguments?. Personally, the problem with this
implementation is that the argument list needs to be void, otherwise some
arguments need construction first and some may or may not be default
constructible (actually some implementations do assume such).
To solve this problem, I am thinking about using member function pointer
-- if a member function can be assigned to a member function pointer with
the right signature, then the member function exists. So my implementation
is like (to test whether there exist a ::foo( int ) member function:
template< class T >
struct TestFoo {
typedef void(T::*FP)( int );
FP fp = & Foo::foo;
static auto test( T * p ) -> decltype( fp = & T::foo, std::true_type() );
static auto test( ... ) -> std::false_type;
};
This implementation works but a weird thing is that I have to move the
declaration of fp outside of decltype( ... ), otherwise the compiler (gcc
version 4.8.1) complains:
static auto test( T * p ) -> decltype( FP fp = & T::foo, std::true_type() );
^ error: expected ')' before 'fp'
I am kinda new to decltype and I am just curious whether it allows local
variables or may be other problems? I am also open to suggestions on the
member function pointer approach. Thanks in advance!
No comments:
Post a Comment