1

我想实现这样的目标:

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 参数列表上指定内部容器的类型或其迭代器。

有什么办法可以优雅地解决这个问题吗?

4

1 回答 1

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;
}

现场示例在这里

于 2013-05-13T11:56:17.193 回答