可调用模板(回调)作为类模板参数

时间:2013-05-13 10:52:00

标签: c++ templates c++11 generic-programming

我想实现这样的目标:

template<class IT>
size_t foo(IT begin,IT end) {return end-begin;}  

template<template (class) class FOO>
class BAR
{
  public:
  any_container<any_type> container;
  size_t call_foo
  {
    FOO<any_container<any_type>::iterator>(container.begin(), container.end());
  }
};

此外,我希望能够将函数,lambda或函数对象作为FOO传递。 此处可能应使用std::function,但无法使用任意类型std::function<size_t(T,T)>声明T。 我绝对不希望在模板BAR参数列表中指定内部容器的类型或其迭代器。

有没有办法以优雅的方式解决这个问题?

1 个答案:

答案 0 :(得分:0)

根据您的评论,我认为您正在寻找类似的内容:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <utility>
#include <vector>

struct Sender {

  template<typename Iter>
  std::size_t operator()(Iter begin, Iter end) {
    for(Iter cur = begin; cur != end; ++cur) {
      // your low-level send stuff
    }
    return (end - begin);
  }
};

struct Receiver {

  template<typename Iter>
  std::size_t operator()(Iter begin, Iter end) {
    for(Iter cur = begin; cur != end; ++cur) {
      // your low-level receive stuff
    }
    return (end - begin);
  }
};

template<typename Fn>
struct Bar
{
protected:
  Fn _fn;
public:
  Bar(Fn fn) : _fn(std::move(fn)) { }

  template<typename Container>
  std::size_t call_fn(Container & container)
  {
    return _fn(std::begin(container), std::end(container));
  }
};

template<typename Fn>
auto create_bar(Fn && fn) -> Bar<typename std::remove_reference<Fn>::type> {
  return { std::forward<Fn>(fn) };
}

用法很简单:

template<typename Iter>
std::size_t my_foo(Iter begin, Iter end) {
  return (end - begin);
}

int main(int argc, char ** argv) {
  typedef typename std::vector<int>::iterator iter;
  // functors
  auto functor = create_bar(Sender());
  // lambdas
  auto lambda = create_bar([](iter begin, iter end) -> std::size_t { return (end - begin); });
  // plain old functions
  auto function = create_bar(&my_foo<iter>);

  std::vector<int> tmp = { 0, 1, 2, 5};

  std::cout << "Functor: " << functor.call_fn(tmp) << std::endl;
  std::cout << "Lambda: " << lambda.call_fn(tmp) << std::endl;
  std::cout << "Function: " << function.call_fn(tmp) << std::endl;

  return 0;
}

实例here