模板函数中的错误以获取来自C 输入函数的参数类型

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

本文关键字:函数 输入 参数 类型 错误 获取      更新时间:2023-10-16

我遇到了一些类似的问题,并找到了这个问题:是否可以找出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;
  };  
};

就我而言,(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
}

我在下面收到编译错误:

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

为什么可以在参数类型不能时汇编返回类型,我该如何使其工作?

使用TypeName和模板:

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

一行说明:

  • 为什么要typename?因为::type是一种因类型。
  • 为什么template?因为arg<>是一个因模板。

希望会有所帮助。