Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in template function to get the parameter type from input function in C++?

I met some similar problem and find this question: Is it possible to figure out the parameter type and return type of a lambda?.

I use the code in the answer of that question:

#include <iostream>
#include <tuple>

template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())> {}; 

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const> {
  enum { arity = sizeof...(Args) };

  typedef ReturnType result_type;

  template <size_t i>
  struct arg {   
  typedef typename std::tuple_element<i, std::tuple<Args...>>::type type;
  };  
};

In my case, the (lambda)function is user-defined, so I must use a template function to do something based on the user-defined function, so I add a proxy function below:

template <class F>
void proxy(F func) {
  typedef function_traits<decltype(func)> traits;
  typename traits::result_type r;
  traits::arg<0>::type p;                          // compile error
}

I get the compiling error below:

error: `::type` has not been declared
error: expected `;` before `p`

Why return type can be compiled while parameter type can not, how can I make it work?

like image 984
xunzhang Avatar asked Feb 11 '26 23:02

xunzhang


1 Answers

Use typename and template:

typename traits::template arg<0>::type p;    

One line explanations:

  • Why typename? Because ::type is a dependent type.
  • Why template? Because arg<> is a dependent template.

Hope that helps.

like image 118
Nawaz Avatar answered Feb 13 '26 16:02

Nawaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!