在默认模板功能参数上

时间:2012-09-04 03:27:27

标签: c++ templates

我想设计一组函数,例如minmaxstddev,它们可以支持用户定义的类型。我打算做的是让用户将Extractor模板参数传递给这些函数。一些示例代码如下:

template <typename T>
struct DefaultExtractor
{
  typedef T value_type;
  static T value(T &v){
    return v;
  }
};

template <
  typename Extractor=DefaultExtractor<typename std::iterator_traits<InputIterator>::value_type>, //error
  typename InputIterator>
typename Extractor::value_type 
foo(InputIterator first, InputIterator last)
{
  return Extractor::value(*first);
}

这不编译,错误消息是&#34;错误:'InputIterator'未在此范围内声明&#34;在typename Extractor=...

的行

我想在Extractor之前放置模板InputIterator的原因是,当用户想要使用自定义的foo来呼叫Extractor时,他们不会InputIterator。需要明确提供InputIterator的类型。

我想知道是否有一个解决方案来编译代码,同时它不需要用户在需要自定义Extractor时明确提供参数g++-4.6.1 -std=c++0x

代码使用{{1}}编译。

1 个答案:

答案 0 :(得分:3)

虽然我发现您希望将提取器作为模板参数传递,但实际上将对象传递给函数更为典型。它也更灵活,因为它允许你有额外的状态,可以传递给提取器。

最重要的是,它可以更轻松地处理模板参数:

#include <iterator>
#include <list>

template <typename T>
struct DefaultExtractor
{
  typedef T value_type;
  static T value(T &v){
    return v;
  }
};

struct MyExtractor {
  typedef int value_type;
  static int value(int value) { return value; }
};

template <typename Extractor, typename InputIterator>
inline typename Extractor::value_type
foo(
  InputIterator first,
  InputIterator last,
  const Extractor &extractor
)
{
  return extractor.value(*first);
}

template <typename InputIterator>
inline typename DefaultExtractor<
  typename std::iterator_traits<InputIterator>::value_type
>::value_type
foo(
  InputIterator first,
  InputIterator last
)
{
  typedef DefaultExtractor<typename std::iterator_traits<InputIterator>::value_type> Extractor;
  return foo(first,last,Extractor());
}


int main(int argc,char **argv)
{
  std::list<int> l;

  // Use default extractor
  foo(l.begin(),l.end());

  // Use custom exractor.
  foo(l.begin(),l.end(),MyExtractor());
  return 0;
}