根据您的评论,我认为您正在寻找这样的东西:
#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;
}
现场示例在这里