【问题标题】:Error in template function to get the parameter type from input function in C++?从 C++ 中的输入函数获取参数类型的模板函数出错?
【发布时间】:2014-01-22 16:32:46
【问题描述】:

我遇到了一些类似的问题,发现这个问题:Is it possible to figure out the parameter type and return type of a 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`

为什么返回类型可以编译而参数类型不能编译,我该如何让它工作?

【问题讨论】:

    标签: c++ templates c++11 lambda typetraits


    【解决方案1】:

    使用类型名和模板:

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

    一行解释:

    • 为什么是typename?因为::type 是依赖类型。
    • 为什么是template?因为arg&lt;&gt; 是一个依赖模板。

    希望对您有所帮助。

    【讨论】:

    • +1:对template 和typename can be found here 的使用进行了出色的谩骂。
    • @Nawaz 如果 p 是 reference 类型怎么办?
    • @xunzhang:我不明白你在问什么。让我解释一下:p 是一个变量,而不是一个类型,它的类型是typename traits::template arg&lt;0&gt;::type,它可以是一个引用。那么你的问题是什么?
    • @Nawaz 我的问题是,如果typename traits::template arg&lt;0&gt;::type 是引用类型,我想将其转换为原始类型。例如,如果typename traits::template arg&lt;0&gt;::type 是const vector&lt;int&gt;&amp;,我想将其转换为vector&lt;int&gt;
    • @xunzhang:使用std::remove_cv 和std::remove_reference。示例:typename std::remove_cv&lt;typename std::remove_reference&lt;T&gt;::type&gt;::type p;。丑陋,但它的工作!您可以改进用法,如果您将其包装在别名中为 template&lt;typename T&gt; using bare_type = typename std::remove_cv&lt;typename std::remove_reference&lt;T&gt;::type&gt;::type; ... 那么 bare_type&lt;T&gt; p; 将是语法。
    猜你喜欢
    • 2021-07-22
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2015-09-19
    • 1970-01-01
    相关资源
    最近更新 更多