【发布时间】:2014-08-03 14:42:54
【问题描述】:
我一直在尝试创建这个类,它可以使用默认函子作为参数,或者用户可以根据需要提供一个。但我无法将函数指针作为模板参数传递。你能帮我理解我错过了什么吗?
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)作为一个类型(class _Pr) -
我可以用我的 MyCLass 做点什么,让它同时接受 functionPtr 和 Functors。我想保持 MyClass 的简单使用。
标签: c++ templates function-pointers functor