在编写一个接受谓词函数的函数时,例如下面的函数;如何确保谓词函数有效(即返回类型operator()
有效)?
template <typename Predicate>
std::vector<SomeType> SearchList( Predicate func )
{
std::vector<SomeType> vecResults;
for( const auto& someObj : someTypeList )
{
if( func( someObj ) )
vecResults.emplace_back( someObj );
}
return vecResults;
}
环顾 C++11 中的 type-traits 工具,我发现std::is_convertible<From,To>
它看起来应该有所帮助,尽管我不确定如何使用它来检查是否存在从operator()
to的合适的隐式转换bool
。我能想到的唯一的事情是:
static_assert( std::is_convertible<Predicate(SomeType), bool>::value, "Predicate type must be convertible to bool" );
或者:
static_assert( std::is_convertible<Predicate::operator()(SomeType), bool>::value, "Predicate type must be convertible to bool" );
但这些对我来说似乎都不正确。