【问题标题】:Get result type of function获取函数的结果类型
【发布时间】:2011-01-10 14:34:31
【问题描述】:

我想特化一个声明为的模板函数:

template<typename Type> Type read(std::istream& is);

然后我有很多静态实现

static int read_integer(std::istream& is);

a.s.o.现在我想做一个宏,这样读取的特化就很简单了:

SPECIALIZE_READ(read_integer)

所以我想我会采用 boost::function_traits 的方式并将 SPECIALIZE_READ 声明为:

#define SPECIALIZE_READ(read_function) \
   template<> boost::function_traits<read_function>::result_type read(std::istream& is) { \
      return read_function(is); \
   }

但是 VC++ (2008) 编译器抱怨:“boost::function_traits”:“read_integer”不是参数“函数”的有效模板类型参数

想法?

【问题讨论】:

  • 那是因为您将值(read_function)作为类型传递。在 C++03 中它不会那样工作。在 C++0x 中,您可以使用 decltype(read_function)。
  • 嗯,是吗?我还应该通过什么?过去我已经成功地将 function_traits 与类方法一起使用,我也将它与函数一起使用,但我不知道为什么它在这种情况下不起作用......

标签: c++ function boost typetraits


【解决方案1】:

据我所知,没有任何机制(除了 C++0x 中的 decltype)可以从函数指针获取返回类型,而无需将相同的函数指针作为参数传递。

最简单的方法是接受重复的返回类型:

#define SPECIALIZE_READ(type, read_function) \
   template<> type read(std::istream& is) { \
      return read_function(is); \
   }

SPECIALIZE_READ(int, read_integer)

【讨论】:

  • 是的,这是我的 B 计划。即使它不那么“整洁”,我也会这样做;)
【解决方案2】:

也许我错了,但如果我清楚地记得我在 C++ 编程期间所经历的事情,那么函数可能不会因为返回类型的不同而被重载。我想如果你这样做,这些东西会起作用:

template<typename Type> void read(std::istream& is, Type& objectToRead);

并使用类型作为参数。如果我没记错的话,这与编译器通常修饰 c++ 名称的方式有关。

【讨论】:

  • 实际上,函数模板仅根据返回类型重载的频率很高,例如在返回类型上使用 enable_if 习惯用法时。
  • 是的,重载没有问题,我在需要的地方简单地使用 read read 等。问题似乎是 boost::function_traits 无法识别我传递给它的静态函数...
  • 是的,返回类型的重载对于非模板函数来说是一个问题,因为在这种情况下,您没有方法可以选择正确的方法。使用模板函数,您可以选择正确的实例化(例如 read&lt;int&gt; - 无需重载决议)
猜你喜欢
  • 1970-01-01
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 2016-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-13
相关资源
最近更新 更多