【问题标题】:In C++, how can I get an arbitrary function's type from its declaration? [duplicate]在 C++ 中,如何从其声明中获取任意函数的类型? [复制]
【发布时间】:2012-07-05 14:41:43
【问题描述】:

可能重复:
Extract the return type of a function without calling it (using templates?)

从这个开始(由其他人提供):

int my_function(int, int *, double);

我想解决这个问题:

typedef boost::function_types::result_type< my_function_type >::type my_result;
typedef boost::function_types::parameter_types< my_function_type >::type my_parameters;

我如何获得my_function_type

注意:我知道BOOST_TYPEOF(),但它似乎有点吓人,比如“也许不是完全便携”?

【问题讨论】:

  • 函数可以重载,还是您明确不想处理这种情况?哦,你可能还需要 C++11。
  • @R.MartinhoFernandes:我可以指定函数是纯“C”风格,因此不会重载。
  • C++11 关键字decltype 将允许您这样做。我认为仅使用 C++03 没有任何简单的方法。
  • @DavidH:我知道你还在等待答案。您在寻找 C++03 解决方案吗?
  • @phresnel:是的,这就是我的想法,尽管我确信这是不可能的。

标签: c++ templates boost c++11 metaprogramming


【解决方案1】:

decltype。例子:

char foo(int) {}
decltype (foo(3)) const *frob = "hello foo";
typedef decltype (foo(3)) typeof_foo;
using typeof_foo = decltype(foo(3));

decltype 的表达式在编译时进行评估,因此必须是可解析的。您可以将任何constexpr 整数传递给它。

【讨论】:

    【解决方案2】:

    这取决于你想做什么。体内的

    template <typename T>
    void foo(T )
    {
      // ...
    }
    

    如果您调用foo(my_function),T 是您的函数的类型。使用 c++03-features 无法解决您的问题,否则不会将 decltype 添加到核心语言中。

    【讨论】:

      【解决方案3】:

      模板魔法来了(不涉及Boost):

      template <typename ReturnType> class clFunc0
      {
          typedef ReturnType ( *FuncPtr )();
      public:
          typedef ReturnType Type;
      };
      
      template <typename ReturnType> inline clFunc0<ReturnType> ResultType( ReturnType ( *FuncPtr )() )
      {
          return clFunc0<ReturnType>();
      }
      
      #define FUNC_TYPE( func_name ) decltype( ResultType( &func_name ) )::Type
      
      int test()
      {
          return 1;
      }
      
      int main()
      {
          FUNC_TYPE( test ) Value = 1;
      
          return Value;
      }
      

      然后编译通过

      gcc Test.cpp -std=gnu++0x
      

      【讨论】:

      • 虽然还在使用 decltype,这似乎是之前答案的共识
      • 像程序员一样老实说:为什么不把你的代码简化为int test(){return 1;} int main() {decltype (test()) v = 1; return v;}
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多