Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Function pointer as Template argument instead of functor

I have been trying to create this class which can either use the default functor as an argument or the user can provide one if he wants. But I am unable to pass function pointer as my template argument. Can you please help me in understanding what I am missing.

template <typename T>
struct CheckFunctor
{
    bool operator()(T obj)
    {
        return true;
    }
};



template <typename _Ty,
class _Pr = CheckFunctor<_Ty>
>
class MyClass
{
    typedef _Ty                     mapped_type;
    typedef _Pr                     CanBeCleaned_type;

    _Ty data;
    CanBeCleaned_type predicate;

public:  

    void SomeMethod()
    {
            if( predicate(data))
            {
              std::cout << "Do something";
            }
    }
       MyClass(_Ty timeOutDuration, _Pr pred = _Pr())
        : data( timeOutDuration), predicate( pred)
    {}   
};

template< typename T>
struct CheckEvenFunctor
{
   bool operator()(T val)
    {
       return (val%2 == 0);
    }
};


bool CheckEven( int val)
{
    return (val%2 == 0);
}

int main()
{
//Usage -1
    MyClass<int> obj1( 5);

//Usage- 2
 MyClass< int, CheckEven> obj2(6, CheckEven);  //Error: 'CheckEven' is not a valid template type argument for parameter '_Pr'

 //Usage -3 
 MyClass<int, CheckEvenFunctor<int>>( 7);
}
like image 597
SumitV Avatar asked Feb 12 '23 08:02

SumitV


1 Answers

You are trying to pass CheckEven as a type parameter even though CheckEven is not a type but a function (of type bool(int)). You should define the type as a pointer to the type of function that you are passing. decltype is handy here:

MyClass< int, decltype(&CheckEven)> obj2(6, CheckEven);

You can also create a factory function and let the compiler deduce the template parameters:

template<class T, class F>
MyClass<T, F> makeClass(T timeOutDuration, F pred) {
    return {timeOutDuration, pred};
}

auto obj2 = makeClass(6, CheckEven);
like image 50
eerorika Avatar answered Feb 15 '23 11:02

eerorika