【问题标题】:Detecting function parameter type检测函数参数类型
【发布时间】:2012-11-30 12:34:07
【问题描述】:

我使用以下代码来检测给定函数的长参数。

所以,给定:

int f(int *) { return 0; }

我要提取int *

这是我的尝试:

template<class T, class U> struct SingleArg {
    typedef U MyArg;
};

template<class T, class U> SingleArg<T, U> fT(T (*p)(U));

int main() {
    std::result_of<decltype(fT(f))>::type::MyArg t;
}

但这不起作用,gcc 4.6 给出错误

> error: std::result_of<SingleArg<int, int*> >::type has not been
> declared

所以,我有两个问题:

a) 上面的代码有什么问题?

b) 是否有可能以任何其他方式/方式做到这一点?

【问题讨论】:

  • “函数返回类型”,“检测长参数”。你真正想要什么?
  • 是的。想检测函数参数类型。将修改帖子标题
  • decltype(fT(f))::MyArg?为什么还要使用result_of?它做了一些完全不同的事情(并且有不同的使用语法)。
  • 嗯,编译器错误。 template&lt;class T&gt; using Alias = T; Alias&lt;decltype(fT(f))&gt;::MyArg。如果 GCC 4.6 没有使用别名,请使用 template&lt;class T&gt; struct identity{ typedef T type; },然后使用 identity&lt;decltype(fT(f))&gt;::type::MyArg
  • 出于兴趣,检测类型的目的是什么?如果有办法在没有这个的情况下实现你的更大目标,我会推荐它。

标签: c++ c++11 decltype result-of


【解决方案1】:
#include <type_traits>

template <typename Function>
struct arg_type;

template <class Ret, class Arg>
struct arg_type<Ret(Arg)> {
  typedef Arg type;
};


int f(int *) {
  return 0;
};

int main(int, char**) {
  static_assert(std::is_same<int*, arg_type<decltype(f)>::type>::value, "different types");
}

【讨论】:

    【解决方案2】:
    int f(int *) { return 0; }
    
    template<class T, class U> struct SingleArg {
        typedef U MyArg;
    };
    
    
    template<typename T> 
    struct the_same_type
    {
     typedef T type;   
    };
    
    template<class T, class U> SingleArg<T, U> fT(T (*p)(U));
    
    int main() {
    
        int k;
        the_same_type<decltype(fT(f))>::type::MyArg t= &k;
        return 0;
    }
    

    【讨论】:

    • 谢谢。这很好用!将此标记为答案,因为这是第一个正确的答案
    【解决方案3】:

    这对我有用:

    // if you want the type
    typedef decltype(fT(f))::MyArg theType;
    
    // if you want the name (may need demangling depending on your compiler)
    std::cout << typeid(decltype(fT(f))::MyArg).name() << std::endl;
    

    关于去杂化,参见例如abi::__cxa_demangle.

    【讨论】:

    • 对我不起作用。 Gcc 在 'thetype' 之前抱怨 'expected initializer'
    • 好的...我正在使用 Apple clang version 4.0-std=c++11,我没有支持 C++11 的 g++ 版本进行测试。
    猜你喜欢
    • 2015-10-24
    • 2011-11-24
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多