2014-04-29 123 views
-1

我想实现相当于std :: function的函数。它应该通过指向函数来创建函子。第一种模板应该是函数的返回类型,下一个将是参数的类型。不过,我想用可变数量的参数来支持函数。这里是我到目前为止的代码:C++实现std :: function与模板

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <functional> 

using namespace std; 

template< typename T, typename... A > 
struct create_functor 
{ 
    template < typename T (*function)(A) > // here I get an error 
    struct functor 
    { 
     T operator()(A... arguments) 
     { 
      return function(arguments); 
     } 
    }; 
}; 

bool less_than(const int& a, const int& b) 
{ 
    return a < b; 
} 

create_functor< bool, const int&, const int& >::functor< &less_than > less_than_int; 

//auto less_than_int_a = std::function< bool(int,int) >(less_than); 

int main() 
{ 
    vector<int> sample; 
    sample.push_back(1); 
    sample.push_back(0); 
    sample.push_back(3); 
    sample.push_back(-1); 
    sample.push_back(-5); 

    sort(sample.begin(), sample.end(), less_than_int); 

    for(int a : sample) 
    { 
     cout << a << " "; 
    } 

    cout << endl; 

    return 0; 
} 

看来我有麻烦传递参数包从外到内的模板(这需要函数指针)

如何通过一个可变数量的任何想法类型的函数声明将不胜感激。

谢谢:)

+0

它没有任何意义,'less_than'是一个函数指针,不是类型,你不能将函数指针作为类型传递给模板参数 –

+0

是的,但是我设法为bool(int,int)函数创建了这个专用化以同样的方式:http://pastie.org/9123706。我猜模板应该把指针指向函数。 – GeneralFailure

+0

你是什么意思? [它不会编译](http://coliru.stacked-crooked.com/a/9751798572bebe3e) –

回答

0

变化

template < typename T (*function)(A) > 

template < T (*function)(A...) > 

我也会改变:

{ T operator()(A... arguments) { return function(arguments); } 

{ 
    template<typename...Ts> 
    T operator()(Ts&&... arguments) const { 
    return function(std::forward<Ts>(arguments)...); 
    } 

为了提高效率。然后我再次不确定这一点。

相关问题