1

在编写一个接受谓词函数的函数时,例如下面的函数;如何确保谓词函数有效(即返回类型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" );

但这些对我来说似乎都不正确。

4

1 回答 1

1

你可以使用:

#include <utility> // For std::declval<>()

static_assert(
    std::is_convertible<decltype(func(std::declval<SomeType>())), bool>::value,
    "Predicate's return type must be convertible to bool");

如果您只有类型Predicate或不想func在表达式中使用:

static_assert(
    std::is_convertible<
        decltype(std::declval<Predicate&>()(std::declval<SomeType>())),
        bool>::value,
    "Predicate's return type must be convertible to bool");
于 2013-06-03T13:51:37.423 回答