문제

I want to implement function which is equivalent to std::function. It should create functor by taking pointer to function. The first type of the template should be the return type of the function, and the next will be the types of the arguments. However I want to support functions with variadic number of arguments. Here's my code so far:

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

It seems I have trouble passing the parameter pack from the outer to the inner template( which takes pointer to function )

Any ideas on how to pass the variadic number of types to the function declaration would be appreciated.

Thanks:)

도움이 되었습니까?

해결책

Change

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

to

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

I would also change:

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

to

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

for efficiency sake. Then again I am unsure of the point of any of this.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top