0xBADF00
0xBADF00

Reputation: 1120

Get number of arguments in a class member function

I am trying to get the number of parameters in a class member function.

template <typename R, typename ... Types> 
constexpr std::integral_constant<unsigned, sizeof ...(Types)> 
FuncArgCount(R(*f)(Types ...))
{
    return std::integral_constant<unsigned, sizeof ...(Types)>{};
}

class TestClass
{
public:
   TestClass(){}

   void On_Test(size_t v)
   {}

   void Call()
   {
       std::cout<< FuncArgCount(&TestClass::On_Test)::value;
   }
};

The above template implementation is taken from this thread and works great on non-member functions Get function parameters count

Upvotes: 0

Views: 581

Answers (1)

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14589

First, you have to overload for pointer to member. Pointers to member aren't actually pointers, they are separate type representing an offset within type.

template <typename R, typename T, typename ... Types> 
constexpr std::integral_constant<unsigned, sizeof ...(Types)> 
FuncArgCount(R(T::*)(Types ...))
{
    return std::integral_constant<unsigned, sizeof ...(Types)>{};
}

Second, the output line should be using . , not ::

 std::cout<< FuncArgCount(&TestClass::On_Test).value;

Or you can return that value directly from function, afaik it's a more logical approach.

Upvotes: 2

Related Questions