Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std :: is_function on member function?

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.

like image 453
Matteo Monti Avatar asked Jan 06 '23 06:01

Matteo Monti


2 Answers

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

like image 170
lisyarus Avatar answered Jan 20 '23 02:01

lisyarus


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
                                    > {};
like image 35
manlio Avatar answered Jan 20 '23 01:01

manlio