C++:函数指针作为模板参数而不是仿函数

标签 c++ templates function-pointers 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++:函数指针作为模板参数而不是仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25105798/

相关文章:

c++ - QT MYSQL驱动构建, undefined reference `mysql_get_client_version@0'

c++ - c++中模板类的容器

c++ - 是否可以访问 C++ 模板模板常量参数?

c++ - 在保留类名的同时弃用类模板的正确程序是什么?

c - C中函数指针的显式解引用

c++ - 指向成员表示的指针

c++ - std::function 的目的是什么以及如何使用它?

c++ - 在 C++ 中使用嵌入式 lua 从外部目录加载文件?

c++ - 使用 SolvePnP 的 OpenCV 断言失败

c++ - 在 C++ 中为 SQL 转义字符串