+-
C:函数指针作为Template参数而不是functor
我一直在尝试创建这个类,它可以使用默认的仿函数作为参数,或者用户可以根据需要提供一个.但我无法将函数指针作为模板参数传递.能帮助我理解我所缺少的东西吗?

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);
}
最佳答案
您试图将CheckEven作为类型参数传递,即使CheckEven不是类型而是函数(类型为bool(int)).您应该将类​​型定义为指向要传递的函数类型的指针. decltype在这里很方便:

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

您还可以创建工厂函数并让编译器推导出模板参数:

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

auto obj2 = makeClass(6, CheckEven);
点击查看更多相关文章

转载注明原文:C:函数指针作为Template参数而不是functor - 乐贴网