在C++中从输入函数获取参数类型的模板函数出错?

xun*_*ang 2 c++ lambda templates type-traits c++11

我遇到了一些类似的问题并找到了这个问题:是否有可能找出lambda的参数类型和返回类型?.

我在这个问题的答案中使用代码:

#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;
  };  
};
Run Code Online (Sandbox Code Playgroud)

在我的例子中,(lambda)函数是用户定义的,所以我必须使用模板函数来根据用户定义的函数做一些事情,所以我在下面添加一个代理函数:

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
}
Run Code Online (Sandbox Code Playgroud)

我得到以下编译错误:

error: `::type` has not been declared
error: expected `;` before `p`
Run Code Online (Sandbox Code Playgroud)

为什么返回类型可以编译而参数类型不能,我怎样才能使它工作?

Naw*_*waz 9

使用typename和template:

typename traits::template arg<0>::type p;    
Run Code Online (Sandbox Code Playgroud)

一行解释:

  • 为什么typename?因为::type是依赖类型.
  • 为什么template?因为arg<>是依赖模板.

希望有所帮助.