Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top