我一直在尝试创建此类,它可以使用默认仿函数作为参数,或者用户可以根据需要提供一个。但是我无法将函数指针作为我的模板参数传递。你能帮我理解我所缺少的吗?
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/