I can do the following to detect if something is a function:
void f()
{
}
int main()
{
std :: cout << std :: is_function <decltype(f)> :: value << std :: endl; // true
}
Now, what happens if I want to do the same, but with a function that is a method of a class?
I naively tried to do something like
class myclass
{
public:
void f()
{
}
};
int main()
{
std :: cout << std :: is_function <decltype(myclass :: f)> :: value << std :: endl;
}
But I get
Call to non-static member function without an object argument
What am I supposed to do? I would like something like the above to.. well, to just print true
.
A member function pointer is not the same as an ordinary pointer to function. Also, myclass::f
is ill-formed without an &
. For member functions there exists std::is_member_function_pointer
.
#include <iostream>
#include <type_traits>
class myclass
{
public:
void f() {}
};
int main()
{
std::cout << std::is_member_function_pointer<decltype(&myclass::f)>::value << std::endl;
}
Live on ideone
decltype(myclass :: f)
is ill-formed.
You can use std::is_member_function_pointer
(std::is_member_function_pointer<decltype( &myclass::f )>::value
).
The interesting thing is a possible implementation of std::is_member_function_pointer
taking advantage of std::is_function
:
template< class T >
struct is_member_function_pointer_helper : std::false_type {};
template< class T, class U>
struct is_member_function_pointer_helper<T U::*> : std::is_function<T> {};
template< class T >
struct is_member_function_pointer : is_member_function_pointer_helper<
typename std::remove_cv<T>::type
> {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With